2014-11-26 2 views
1

Я пытаюсь подсчитать длину имени, которое пользователь вводит с использованием дополнительного метода. .? Когда я пытаюсь получить доступ к пользовательскому вводу «ipnut из моего метода он имеет ошибку, что случилось с моим кодомКак получить доступ к пользовательскому вводу из другого метода

import java.util.Scanner; 

public class LengthOfName { 
    public static void main(String[] args) { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Type your name: "); 
     String input = reader.nextLine(); 


    calculateCharecters(text); 

} 
public static int calculateCharecters(String text){ 

    int texts = input.length(); 
    System.out.println("Number of charecters: " + texts); 
    return texts; 
} 

}

ответ

1

изменение calculateCharecters(text); в calculateCharecters(input);

import java.util.Scanner; 

public class LengthOfName { 
    public static void main(String[] args) { 
     Scanner reader = new Scanner(System.in); 
     System.out.println("Type your name: "); 
     String input = reader.nextLine(); 


    calculateCharecters(input); 

} 
public static int calculateCharecters(String text){ 

    int texts = input.length(); 
    System.out.println("Number of charecters: " + texts); 
    return texts; 
} 
} 
+0

Ах! Я знал, что это легко. Все, что мне было нужно, - это ввести пользователя в параметр. –

+0

это должно быть. у вас нет переменной с именем text. к.т.? – Burusothman

0
calculateCharecters(text); 

Должен быть:

calculateCharecters(input); 

Вам необходимо передать свой ввод в свой метод.

текст - это ваш параметр для метода, который вы вызываете. Вы должны передать вход t o текст.

0

изменения calculateCharecters(text) должны быть calculateCharecters(input)
и input.length() должны быть text.length()

public static void main(String[] args) { 

    Scanner reader = new Scanner(System.in); 
    System.out.println("Type your name: "); 
    String input = reader.nextLine(); //"input" store the user input 

    calculateCharecters(input); //and go through this metod 

} 

public static int calculateCharecters(String text) { // now "text" store the user input 

    int texts = text.length(); //here "texts" store the "text" lenght (text.lenght()) or number 
           //of characters 

    System.out.println("Number of charecters: " + texts); //printing number of characters 
    return texts; //returning number of characters so 
} 

вы можете сделать это в ваш главный

int characterLength = calculateCharacters(input); //because your method return an int 
System.out.println("Number of charecters: " + characterLength);