[英]Limit number of prompted arguments
I want to prompt the user to input just two numbers which represent the size NxN of a board. 我想提示用户仅输入两个数字,它们代表电路板的大小NxN。 If the user write less than 1 or more than 2 numbers, the program don't allow him to do that and instead, handle this by an exception.
如果用户写的数字少于1个或大于2个,则程序不允许他这样做,而应通过异常处理。
For example: 例如:
public class Tester {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Board size NxN: ");
int width = userInput.nextInt();
int height = userInput.nextInt();
}
}
How can achieve this using a try-catch block limiting the user to input only 2 numbers? 如何使用try-catch块将用户限制为仅输入两个数字来实现此目的?
public class Tester { 公共课程测试人员{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Board size NxN: ");
try {
int width = userInput.nextInt();
int height = userInput.nextInt();
if (userInput.hasNext()) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.err.println("Enter just two numbers");
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.