【问题标题】:proper way to read user input from command line in java在java中从命令行读取用户输入的正确方法
【发布时间】:2009-11-15 14:11:17
【问题描述】:

我希望在我从命令行读取用户输入的方式上获得一些关于最佳实践和 cmets 的意见。有没有推荐的方法来做到这一点,我是否正确使用了 try/catch 块?

我的示例在这里运行良好,但仍然想听听是否有“更清洁”的方法来做到这一点。非常感谢。例如,他是否需要在每个 catch 块中返回语句? 或者,我应该将我的逻辑(条件)放在 try 块中吗?

公共类客户端{

public static void main(String[] args) {
    begin();
}

private static void begin(){
    Machine aMachine = new Machine();
    String select=null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while(aMachine.stillRunning()){
        try {
            select = br.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your selection");
            return;
        }catch(Exception ex){
            System.out.println("Error trying to evaluate your input");
            return;
        }

        if (Pattern.matches("[rqRQ1-6]", select)) {
            aMachine.getCommand(select.toUpperCase()).execute(aMachine);
        }
        /*
         * Ignore blank input lines and simply
         * redisplay options
         */
        else if(select.trim().isEmpty()){
            aMachine.getStatus();
        }
        else {                
            System.out.println(aMachine.badCommand()+select);
            aMachine.getStatus();
        }
    }
}

}

【问题讨论】:

    标签: java exception exception-handling iostream user-input


    【解决方案1】:

    我通常更喜欢使用 Scanner 类来读取输入行。使用扫描器类,您可以请求特定类型(双精度、整数、...、字符串)。这也会为您进行验证测试。

    我不建议您按照您的方式编写输入解析。捕获通用异常将捕获任何东西,例如 MemoryError 等。坚持特定异常并从那里处理它们。如果输入与预期类型不匹配,Scanner 将通过 InvalidInputException(或其他影响)。

    【讨论】:

    • 那么扫描仪不需要使用 try/catch 块和异常处理?
    • 它不需要它,但它会抛出错误的输入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2012-05-29
    • 2012-10-06
    • 1970-01-01
    相关资源
    最近更新 更多