I have to make a text based game in Java for uni and I want to let users use multiple command variations and multiple names for items/NPCs. Whats the best way to do this?
For example, if i want people to go west i want people to be able to say "Go west" or "Head West" or "Walk west", etc.
I understand I can do this with just many of these:
if (command.equals("head") || command.equals("walk") || command.equals("travel") || command.equals("go"))
but not only is this lengthy and ugly but with every single command, every single item and every single character it will become insanely long and inefficient. Is there any better way to do this that isn't insanely advanced? Thanks
CodePudding user response:
If you want you can ignore what user inputs except the real value you want, which I assume is the direction:
String lowerCaseCommand = command.toLowerCase()
if (lowerCaseCommand.contains("west") || lowerCaseCommand.contains("north") || so on...) {
// do something.
}
Or you want something like this:
String[] array = {"head", "walk", "travel"}
for (String str : array) {
if (command.equalsIgnoreCase(str)) {
// do something
break;
}
}
CodePudding user response:
You could (if you wanted) use a switch/case block, for example:
switch (command.toLowerCase()) {
case "head": case "walk": case "travel":
callDoSomethingMethod();
break;
case "rest": case "sleep": case "passout":
callAnotherDoSomethingMethod();
break;
default:
System.err.println("Don't understand the command: '" command "!"
}