简体   繁体   中英

checking if something is equal to different things java

for example:

if(!UserInputSplit[i].equalsIgnoreCase("the" || "an")

produces a sytax error. What's the way around this?

You need to explicitly compare with each String.

Example:

if(!UserInputSplit[i].equalsIgnoreCase("the") || !UserInputSplit[i].equalsIgnoreCase("an"))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM