Java Scanner需要两个输入

时间:2017-11-07 17:32:01

标签: java java.util.scanner

我已经用几种不同的方式重新安排了我的代码而没有运气。我认为问题在于我不完全理解Java中的Scanner。无论哪种方式,这是我的代码。它首先从传递给方法的数组中打印菜单。接下来,它应该等待用户的输入并将用户输入解析为整数。

int menuLength = menuItems.length;

Scanner scnr = new Scanner(System.in); //Create a new scanner object
int userInput = 0; //Initialize the input variable
int i=0; //Initialize the counter variable

for (i=0; i < menuLength; ++i) {//loop until it has reached the end of the menu
    System.out.println((i+1) + ". " + menuItems[i]);//Print menu items
}

System.out.print(">>");

userInput = Character.getNumericValue(scnr.next().charAt(0));

while ((userInput < 1) || (userInput > menuLength)) { //Loop while the value is not a valid selection
        System.out.println("Error, please select from the menu options.");
        while (scnr.hasNextInt()!=true) { //Loop while the value is not an integer
            System.out.println("Error, please select from the menu options.");
            //LOOP TO PROVIDE THE MENU
            for (i=0; i < menuLength; ++i) {//loop until it has reached the end of the menu
                System.out.println((i+1) + ". " + menuItems[i]);//Print menu items
            }
            System.out.println(">>");
            scnr.next(); //Get the next value
        }

        for (i=0; i < menuLength; ++i) {//loop until it has reached the end of the menu
            System.out.println((i+1) + ". " + menuItems[i]);//Print menu items
        }

        System.out.print(">>");
        userInput =  scnr.nextInt(); //Get the next value
    }

代码在此处停止并要求用户输入内容,按Enter键,然后再次输入内容,并在进入下一行之前按Enter键。我只是希望用户能够输入一个值,按回车键,然后它会启动一个错误陷阱循环。

0 个答案:

没有答案