【问题标题】:Limit number of prompted arguments限制提示参数的数量
【发布时间】:2016-03-01 05:34:29
【问题描述】:

我想提示用户只输入两个代表棋盘大小 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 块来实现这一点?

【问题讨论】:

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


    【解决方案1】:

    公共类测试者{

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

    }

    【讨论】:

    • 当我输入第一个数字,然后输入第二个数字时,我按下回车键,它会继续等待第三个数字。当输入第三个数字时,它会抛出异常:Board size NxN: 2 3 8 "Enter just two numbers"
    • 这是合乎逻辑的。您需要向用户显示提示,例如“输入第一个”、“输入第二个”、“正确(y/n)?”,并且只接受“YyNn”作为最后一个的输入(并且只接受第一个的数字)。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2020-06-04
    相关资源
    最近更新 更多