int choice = 0;
boolean isRight = true;
while (isRight){
try {
isRight = false;
choice = input.nextInt();
}
catch (InputMismatchException ex){
System.out.println("Please enter just one number!");
isRight = true;
}
}
想检测用户的输入是否是整数,如果不是就让他再输。一开始报错了,代码如上。后改正,代码如下:
int choice = 0;
boolean isRight = true;
while (isRight){
try {
Scanner input1 = new Scanner(System.in);
isRight = false;
choice = input1.nextInt();
}
catch (InputMismatchException ex){
System.out.println("Please enter just one number!");
isRight = true;
}
}
原来需要重新Scanner一下,否则之前的的输入一直残留在其中,就会一直报错。
网友评论