Continuous input commands

2019-06-02 07:18发布

问题:

My program will read user keyboard commands in the form of "command parameter" with a space in between. It keeps carrying out individual commands until the next command is "exit". Also, if the user messes up, the program should show an error but continue asking for commands (a feature I don't think I have completed)..

Is the following code a good way of implementing this? Could it handle the user simply pressing the enter key w/o a command, junk input, etc? If anything, I would love to know if there is a better idiomatic way implementing this.

String command = "";
String parameter = "";
Scanner dataIn = new Scanner(System.in);

while (!command.equals("exit")) {
    System.out.print(">> ");

    command = dataIn.next().trim();
    parameter = dataIn.next().trim();
    //should ^ these have error handling?

    if (command.equals("dothis")) {
        //do this w/ parameter..
    } else if (command.equals("dothat")) {
        //do that w/ parameter..
    } //else if... {}
      else {
        system.out.println("Command not valid.");
    }
}

System.out.println("Program exited by user.");

Note: I took this class without a single notion of what exception handling is, so any pointers in that area is greatly appreciated :)

回答1:

This is a simple way to implement an input loop:

Scanner sc = new Scanner(System.in);

for (prompt(); sc.hasNextLine(); prompt()) {

    String line = sc.nextLine().replaceAll("\n", "");

    // return pressed
    if (line.length == 0) 
        continue;

    // split line into arguments
    String[] args = line.split(" ");    

    // process arguments
    if (args.length == 1) {
        if (args[0].equalsIgnoreCase("exit"))
            System.exit(0);
        if (args[0].equalsIgnoreCase("dosomething"))
            // do something
    } else if (args.length == 2) {
        // do stuff with parameters
    } 
}

Assuming prompt() prints out the prompt here.