如何从另一个方法访问用户输入

时间:2014-11-26 19:42:25

标签: java user-input

我正在尝试使用其他方法计算用户输入的名称的长度。当我尝试从我的方法访问用户输入“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;
}

}

3 个答案:

答案 0 :(得分: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;
}
}

答案 1 :(得分:0)

calculateCharecters(text);

应该是:

calculateCharecters(input);

您需要将输入传递给您的方法。

text是您调用方法的参数。您应该将输入传递给文本。

答案 2 :(得分: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);