我有一个do while循环。检查x在两个值之间。现在,我应该输入一个int值,但是如果用户键入一个double,则会获取异常。我如何在同一个if语句中合并一个检查,以便如果用户键入一个双精度字,它会打印类似“ x必须是介于10和150之间的整数”的内容:
do {
x = sc.nextInt();
if ( x < 10 || x > 150 ) {
System.out.print("x between 10 and 150: ");
} else {
break;
}
最佳答案
您可以使用while (true)
捕获异常并对其进行处理,以允许用户重试。
这是我的代码:
Scanner sc = new Scanner(System.in);
do {
System.out.print("\nInsert a number >>> ");
try {
int x = sc.nextInt();
System.out.println("You inserted " + x);
if (x > 10 && x < 150) {
System.out.print("x between 10 and 150: ");
} else {
break;
}
} catch (InputMismatchException e) {
System.out.println("x must be an int between 10 and 150");
sc.nextLine(); //This line is really important, without it you'll have an endless loop as the sc.nextInt() would be skipped. For more infos, see this answer http://stackoverflow.com/a/8043307/1094430
}
} while (true);