在Java中从命令行读取用户输入的正确方法 [英] proper way to read user input from command line in java

查看:496
本文介绍了在Java中从命令行读取用户输入的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望就从命令行读取用户输入的方式获得有关最佳做法和评论的意见。是否有推荐的方法来执行此操作,我是否正确使用了try / catch块?

I was hoping to get some opinions regarding best practices and comments on the way I read user input from the command line. Is there a recommended way to do this, am I using the try/catch blocks properly?

我的示例在这里工作正常,但仍然想听听是否有清洁的方式来做到这一点。非常感谢。例如,他是否需要在每个catch块中返回语句?
还是应该将我的逻辑(条件语句)放在try块中?

My example here works fine, but would still like to hear if there is a 'cleaner' way to do this. Many thanks. For example are he return statements in each catch block necessary? Or, should I put my logic (the conditionals) within the try block?

公共类客户端{

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

}

推荐答案

我通常会使用Scanner类从输入行读取内容。使用扫描器类,您可以请求特定的类型(双精度,整数,...,字符串)。

I typically perfer to use the Scanner class to read from the input line. With the scanner class you are able to request specific types (double, int, ..., string). This will do validation testing for you as well.

我不建议您以这种方式编写输入解析。捕获一个通用的异常会从MemoryError等中捕获任何东西。坚持使用特定的异常并从那里处理它们。如果输入与预期的类型不匹配,则扫描程序将通过InvalidInputException(或可能会影响到的结果)。

I wouldn't recommend writing the input parsing in a way you did. Catching a generic Exception will catch anything, from a MemoryError etc. Stick with specific exceptions and deal with them from there. A Scanner will through an InvalidInputException (or something to that affect) if the input does not match the expected type.

这篇关于在Java中从命令行读取用户输入的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆