这个问题在这里已有答案:
我希望程序在捕获异常时重新执行while循环 - 接收文本输入的异常。相反,它继续使用下面的代码循环,我希望它再次要求用户输入。
import java.util.InputMismatchException;
import java.util.Scanner;
public class NumberGuess {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int between = 100;
int secretNumber = (int)(Math.random()*between);
int inputNum = 0;
int guesses = 0;
System.out.println("Please enter your guess: ");
inputNum = Scanner.nextInt();
guesses++;
// #### Loop here ####
while (inputNum != secretNumber) {
// Try catch
try {
// number too high or too low
if (inputNum > 100 | inputNum < 0) {
System.out.println("Please enter a guess between 0 and " + between + ".");
inputNum = Scanner.nextInt();
}
// less than secretNumber
if (inputNum < secretNumber) {
System.out.println("Try higher");
inputNum = Scanner.nextInt();
guesses++;
}
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Try lower");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
}
}
System.out.println("\nWell done! The secret number was " + secretNumber + "." + "\nYou took " + guesses + " guesses.");
}
}
输出:
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
Invalid Input
Try higher
研究Scanner
上的文档:
当扫描程序抛出
InputMismatchException
时,扫描程序将不会传递导致异常的令牌,因此可以通过其他方法检索或跳过它。
如果您发现异常,则在尝试读取数字之前,扫描仪将保留原样。你必须在追踪区内用nextLine
推进它。
|
是合乎逻辑的运营商。使用条件||
if (inputNum > 100 || inputNum < 0) {
进行2次更改,如下所示可以帮助您实现所需的功能。
1将if (inputNum > 100 | inputNum < 0) {
更改为if (inputNum > 100 || inputNum < 0) {
如果输入非数字数字(例如a),则可以捕获InputMismatchException异常。
Scanner.next()
以便可以在Console中重新输入数字。更改
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Try lower");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
}
至
// greater than secretNumber
if (inputNum > secretNumber) {
System.out.println("Try lower");
inputNum = Scanner.nextInt();
guesses++;
}
}
catch(InputMismatchException e){
System.out.println("Invalid Input");
Scanner.next();
}
通过以上更改,测试如下:
Please enter your guess:
60
Try higher
80
Try higher
90
Try lower
a
Invalid Input
Try lower
80
Try higher
85
Try lower
84
Try lower
83
Try lower
82
Try lower
81
Well done! The secret number was 81.
You took 9 guesses.