尝试使用hasNextInt((,但除非输入无效输入,否则不会终止。
Scanner sc= new Scanner(System.in);
int total=0; int temp;
while(sc.hasNextInt()) {
temp=sc.nextInt();
if(temp>0&&temp<17)total +=200;
else {
System.out.println("Invalid input"); break;
}
} System.out.println(total);
您可以执行类似的操作
Scanner sc = new Scanner(System.in);
String input = null;
do {
input = sc.nextLine();
try {
int temp = Integer.parseInt(input);
System.out.println("do your logic here, input was "+temp);
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("invalid input, terminating");
break;
}
} while (!"".equals(input));
System.out.println("--- end ---");
或者这个
Scanner sc = new Scanner(System.in);
while (true) {
String input = sc.nextLine();
if ("".equals(input)) {
break;
}
try {
int temp = Integer.parseInt(input);
System.out.println("do your logic here, input was " + temp);
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("invalid input, terminating");
break;
}
}
System.out.println("--- end ---");