I am trying to make it so anytime a user enters ."insert word here" the program will recognize this an invalid command and send the user a message saying something like "invalid command type .help for a list of commands". I already have my active commands working but Im not sure how to catch invalid commands here is my code so far.
while (true) {
String userInput = scan.nextLine();
if (userInput.equals(".help")) {
//print list of commands
}
else if (userInput.equals(".ping") {
//print pong
}
//check for any String that starts with . but does not equal the previous commands and return an error message
}
CodePudding user response:
You could use a switch
statement to handle unknown commands:
while (true) {
String userInput = scan.nextLine();
switch(userInput) {
case ".help":
// print list of commands
break;
case ".ping":
// print pong
break;
default:
// print error message for unknown command
}
}
CodePudding user response:
You can use the startsWith method to check if the user's input starts with a period, and then use the equals method to check if it is not equal to any of the valid commands. Here is an example:
while (true) {
String userInput = scan.nextLine();
if (userInput.equals(".help")) {
// print list of commands
} else if (userInput.equals(".ping")) {
// print pong
} else if (userInput.startsWith(".")) {
System.out.println("Invalid command. Type .help for a list of commands.");
}
}
CodePudding user response:
while (true) {
String userInput = scan.nextLine();
if (userInput.equals(".help")) {
//print list of commands
} else if (userInput.equals(".ping")) {
//print pong
} else if(userInput.startsWith(".")) {
// applies if userInput starts with "." but is not .help or .ping
}
else {
// applies if userInput does not start with a "."
}
}