我需要在不输入任何特殊值的情况下终止输入序列,只需按空回车键即可

  • 本文关键字:回车 情况下 任何特 终止 java
  • 更新时间 :
  • 英文 :


尝试使用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 ---");

最新更新