限制提示参数的数量

时间:2016-03-01 05:34:30

标签: java exception-handling try-catch java.util.scanner

我想提示用户只输入两个代表电路板尺寸NxN的数字。如果用户写的数少于1或超过2个,则程序不允许他这样做,而是通过异常处理。

例如:

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();
}
}

如何使用try-catch块来限制用户只输入2个数字?

1 个答案:

答案 0 :(得分:0)

公共类测试员{

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");
    }
}

}