Continuous input commands

坚强是说给别人听的谎言 提交于 2019-12-08 07:31:01

问题


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.



来源:https://stackoverflow.com/questions/12396765/continuous-input-commands

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