Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Java "or function" help!?
ok, so I'm writing a text based game and I have points in which the user has to input data (duh). It's really lengthy to create a switch so I did this:
if("north".equals(direction)||"go north".equals(direction)||"walk north".equals(direction)||"north door".equals(direction)){
room = 2;
}
except, it only ends up doing room=2 if I input "north". nothing else works. Any advice?
2 Answers
- llafferLv 78 years agoFavorite Answer
Sounds to me that you'll want to to create a separate method where you pass in the command from the user and it parses it down to one of a small subset of commands.
So you don't have to check for every possible outcome inside your main logic. Use a separate function to trim out what might be 20-30 possible entries down to the 5-6 unique ones that you really care about. So it might look like this:
direction = parseDirection(direction);
if ("north".equals(direction)) {
room = 2; }
---
so direction is both the input to the function and stores the return. Then in your parseDirection method:
private String parseDirection(String direction) {
String ret = "";
if (direction.toLowerCase().contains("north"))
ret = "north";
else if (direction.toLowerCase().contains("south"))
ret = "south";
...
...
return ret;
}
Something like that, so this method will search your strings for what you want and only return the few possible strings that your main method will be looking for.
- 8 years ago
Are you sure using scan.nextLine() instead of scan.next()?
then try what llaffer said