proper way to read user input from command line in java

蓝咒 提交于 2019-12-11 16:47:49

问题


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?

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 class Client {

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

}


回答1:


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.

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.



来源:https://stackoverflow.com/questions/1737611/proper-way-to-read-user-input-from-command-line-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!