proper way to read user input from command line in

2019-09-02 11:13发布

问题:

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.