虽然Loop正在跳过语句

时间:2014-05-08 01:13:42

标签: java if-statement while-loop java.util.scanner

这样做的目的是确保用户不会收到任何不匹配错误。每次他们偶然输入一个String时,我希望程序说“对不起,请从上面选择练习”并给他们选择再次输入答案而不会崩溃。目前,如果用户输入字符串,循环将跳过if语句并继续执行else语句,直到您手动终止它。

int program = 0;    
System.out.println("Enter 1 for Vocabularly exsersises, 2 for Grammer Exercises and 3 for other");

    while (input.hasNext()) {

        if (input.hasNextInt()) 
            program = input.nextInt() ; 
        else 
            System.out.println("Sorry, please choose exercises from above");
    }

2 个答案:

答案 0 :(得分:3)

你需要接受错误输入或跳过它:

//...
} else {
    System.out.println(...);
    input.nextLine();
}

答案 1 :(得分:0)

不要使用while循环。而是使用do while循环。

这是我要做的事情

int program;
System.out.println("Enter 1 for Vocabularly exsersises, 2 for Grammer Exercises and 3 for other");
do {
    try {
       program = input.nextInt();
    } catch (Exception e) {
       System.out.println("Sorry, please choose exercises from above");
    }
}while(program != null);

当您不知道用户将要输入的内容时,do while循环很有用。

try catch语句将捕获错误;在这种情况下,如果用户尝试输入字符串或char值。尝试尝试捕捉更多。它将使编程变得更加容易。

相关问题