(bank is a static int variable declared up top)
boolean valid = true;
Scanner scan = new Scanner(System.in);
while (valid) {
try {
System.out.println("How much money do you want to convert to chips?");
bank = scan.nextInt();
valid = false;
} catch(InputMismatchException ex) {
System.out.println("Thats not right try entering a number between 0 and 2,147,483,647");
//bank = scan.nextInt();
continue;
}
}
如果我取消注释第二个银行= scan.nextInt();我得到相同的InputMismatchError,但我没有另一个try catch,所以它打印出stacktrace。
如何更改此循环以在最后接受新输入?
最佳答案
试试这个代码:
static int bank = 0;
public static void main(String[] args) {
boolean valid = true;
Scanner scan = new Scanner(System.in);
do {
System.out.println("How much money do you want to convert to chips?");
if(scan.hasNextInt()){
bank = scan.nextInt();
valid = true;
}else{
scan.nextLine();
valid = false;
System.out.println("Enter a valid integer value");
}
}while(!valid);
}
希望能帮助到你。
关于java - while循环的扫描器InputMismatchException问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32428176/