0

我希望就我从命令行读取用户输入的方式获得一些关于最佳实践和评论的意见。有没有推荐的方法来做到这一点,我是否正确使用了 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();
        }
    }
}

}

4

1 回答 1

1

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

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

于 2009-11-15T14:25:23.977 回答