This question is in regards to handling continuous user input in a command-line application in Java.
Within Main, I have the following code:
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
String line = sc.nextLine().replaceAll("\n", "");
// return pressed
if (line.length() == 0) {
continue;
}
// split line into arguments
String[] args1 = line.split(" ");
// process arguments
if (args1.length > 0) {
if (args1[0].equalsIgnoreCase("q")) {
System.exit(0);
} else if (args1[0].equalsIgnoreCase("someInput")) {
// Put stuff here
} else {
System.out.println("exiting");
System.exit(0);
}
}
}
As you can tell, this is to handle continuous inputs from the command-line. The program quits if the input is q, and does other stuff when it's someInput. This program is essentially a state machine.
However, this program can get messy very very quick, since it will evolve into a bunch of if-statements and boolean flags to get into the if statements.
For example, as I programmed my current CLI application, it descended into 15+ if-statements, and it's a total MESS in terms of readability and maintainability.
My question is - what is the better way to handle continuous conditional user-input without using a mess of if-statements so it's more readable and maintainable?
Note: The inputs are non-discrete, meaning, it isn't simple string matching.
List. This way, you would ask each "Command" if it was able to process the "input" and if it can, pass it to that "Command" for further processing...