Proper way to read user input from command line in java

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

My example works fine here, but he would still like to hear if there is a “clean” way to do this. Many thanks. For example, it returns statements in each catch block? Or should I put my logic (conditional expressions) in a 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();
        }
    }
}

}

0
source share
1 answer

Scanner . (double, int,..., string). .

, . , MemoryError .. . InvalidInputException ( - ), .

+1

All Articles