Java 如何使方法接受它';在这期间有什么输入?

Java 如何使方法接受它';在这期间有什么输入?,java,methods,java.util.scanner,Java,Methods,Java.util.scanner,我在课堂上有一个作业,但我们必须使用教师的基本代码,而不是按照我们自己的方式设计。注释是该方法的说明,该方法是我到目前为止所拥有的,但我仍然不明白它应该如何工作。让我感到困惑的是,它需要在用户知道该做什么之前打印选项,因此如何在没有输入的情况下运行该方法 /** * Prints the main menu (see output examples), allows the user to make a selection from available operations * * @param

我在课堂上有一个作业,但我们必须使用教师的基本代码,而不是按照我们自己的方式设计。注释是该方法的说明,该方法是我到目前为止所拥有的,但我仍然不明白它应该如何工作。让我感到困惑的是,它需要在用户知道该做什么之前打印选项,因此如何在没有输入的情况下运行该方法

/**
* Prints the main menu (see output examples), allows the user to make a selection from available operations
*
* @param input the Scanner object you created at the beginning of the main
* method. Any value other than the 4 valid selections should generate an
* invalid value prompt. Print the list again and prompt user to select a 
* valid value from the list.

* @return an integer from 1-4 inclusive representing the user’s selection.

*/

public static int mainMenuOptionSelector(Scanner input){
    System.out.println("Please select an option from the list below:");
    System.out.println("1. Check the balance of your account");
    System.out.println("2. Make a deposit");
    System.out.println("3. Withdraw an amount in a specific currency");
    System.out.println("4. End your session (and withdraw all remaining currency in U.S. Dollars)");

    if(input.equals(1))
        return 1;
    else if(input.equals(2))
        return 2;
    else if(input.equals(3))
        return 3;

    else if(input.equals(4))
        return 4;
    else{
        System.out.println("Input falied validation.");
        System.out.println("Please try again");
        return 0;
    }

}
您的方法将a作为输入(除非您的老师使用了自己的扫描仪,否则这将是不好的命名实践)。扫描器提供了从各种来源读取数据的方法,例如键盘(通常是
System.in

其中一种方法是,从扫描仪的输入中读取下一个
int
,然后返回。您可以这样做:

theSelection = input.nextInt();
然后,您可以像引用任何其他int一样引用新变量
theSelection
。请注意
nextInt
方法可能会抛出一些运行时异常,您可能希望捕获并优雅地处理这些异常。

input.equals(1)
没有任何意义。这段代码似乎很不完整。您可能会发现它很有用。也就是说,在代码中,调用
input.nextLine()