限制提示参数的数量



我想提示用户只输入两个数字,代表电路板的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();
}
}

如何使用限制用户仅输入 2 个数字的 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");
    }
}

}

最新更新