Reputation: 761
for example:
if(!UserInputSplit[i].equalsIgnoreCase("the" || "an")
produces a sytax error. What's the way around this?
Upvotes: 0
Views: 238
Reputation: 91
Using a series of || is fine if you've got a small set of items you want to compare against, as explained in an earlier answer:
if (!UserInputSplit[i].equalsIgnoreCase("the") || !!UserInputSplit[i].equalsIgnoreCase("the")) {
// Do something when neither are equal to the array element
}
But, if you have anything greater than a small set of items, you may consider using a map instead, or a set:
// Key = animal, Value = my thoughts on said animal
Map<String, String> animals = new HashMap<String, String>();
animals.put("dog", "Fun to pet!");
animals.put("cat", "I fear for my life.");
animals.put("turtle", "I find them condescending.");
String[] userInputSplit = "I have one dog, a cat, and this turtle has a monocle.".split(" ");
for (String word : UserInputSplit) {
word = word.toLowerCase(); // Some words may be upper case. This only works if the cases match.
String thought = animals.get(word);
if (thought != null) {
System.out.println(word + ": " + thought);
}
}
If you were to go to this approach, of course you'd want to either put it into its own class or somehow have it be loaded once, because you wouldn't want to set up a huge map every time.
Upvotes: 1
Reputation: 66637
You need to explicitly compare with each String.
Example:
if(!UserInputSplit[i].equalsIgnoreCase("the") || !UserInputSplit[i].equalsIgnoreCase("an"))
Upvotes: 5