我有一个while循环。检查x介于两个值之间。现在我应该接受一个int值,但是如果用户输入double im获取异常。我如何在同一个if语句中包含一个检查,这样如果用户键入一个double,它将打印类似“x必须是10到150之间的int:”
do {
x = sc.nextInt();
if ( x < 10 || x > 150 ) {
System.out.print("x between 10 and 150: ");
} else {
break;
}
答案 0 :(得分:4)
您无需额外检查。例外就在那里,所以你可以在你的程序中采取相应的行动。毕竟,输入错误的方式并不重要。只是捕获异常(NumberFormatException,我猜?)并在捕获它时,打印一条错误消息:
while (true) try {
// here goes your code that pretends only valid inputs can occur
break; // or better yet, put this in a method and return
} catch (NumberFormatException nfex) { // or whatever is appropriate
System.err.println("You're supposed to enter integral values.");
// will repeat due to while above
}
答案 1 :(得分:3)
您可以使用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);
答案 2 :(得分:0)
public class SomeClass {
public static void main(String args[]) {
double x = 150.999; // 1
/* int x = (int) 150.999; */ // 2
if ( x >= 10 && x <= 150 ) { // The comparison will still work
System.out.print("x between 10 and 150: " + x + "\n");
}
}
}