我有一个 do while 循环。检查 x 是否在两个值之间。现在我应该接受一个 int 值,但是如果用户输入一个 double 值,我就会得到异常。如何在同一个 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;
}
最佳答案
您不需要额外的支票。异常(exception)就在那里,因此您可以在程序中采取相应的操作。毕竟,输入错误的具体程度并不重要。只需捕获异常(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
}
关于Java:如何测试输入是 double 还是 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19816013/