You have a few errors with your program. The first one is the method you are using to take the user input is incorrect. You should be using the Scanner.nextLine()
method, this will read the user input until a new line character is read (AKA they press enter). Making this modification will make your cmd()
method read something like this:
System.out.print(">");
final Scanner cmd = new Scanner(System.in);
String userInput = cmd.nextLine();
if (userInput.equals("help")) {
help();
} else if(userInput.equals("ping")) {
ping();
}
Additionally you are have some very bad juju inside the help()
method. Inside the help()
method you call the cmd()
method again. To understand why this is bad let me give you a scenario. Pretend your program worked and this is your user input and the -- help outputlisted
was what your help
method printed out.
>help
-- help outputlisted
>help
-- help outputlisted
>help
-- help outputlisted
What would be going on in your program is the none of the methods would ever terminate. You would end up with a call stack like this:
cmd()
help()
cmd()
help()
cmd()
help()
......on and on and on.....
Neither the cmd
or help
method would terminate! You are essentially using recursion, if you built more methods using this design pattern you would surely end up with weird problems. Bottom line is its just bad form.
What you should be doing is using a loop inside your cmd
method. The loop below will keep prompting for user input until the line reads "quit"
. When the user enters quit then the loop will terminate and the cmd()
method will end.
final Scanner cmd = new Scanner(System.in);
String userInput = null;
do {
System.out.print(">");
userInput = cmd.nextLine();
if (userInput.equals("help")) {
help();
} else if(userInput.equals("ping")) {
ping();
}
} while(userInput != null && !userInput.equals("quit"));
Also remove the cmd()
call from your help()
method..
You have a static final
variable named cmd
. Static variables in java should follow the UPPER_SNAKE_CASE naming convention. Also you might rename either the variable or your method. Having them both named cmd
probably isnt the best, also not very descriptive of what it is.