例如:
if(!UserInputSplit[i].equalsIgnoreCase("the" || "an")
产生语法错误。这是怎么回事?
答案 0 :(得分:5)
您需要明确地与每个String进行比较。
示例:
if(!UserInputSplit[i].equalsIgnoreCase("the") || !UserInputSplit[i].equalsIgnoreCase("an"))
答案 1 :(得分:1)
使用一系列||如果您有一小部分要比较的项目,那就没问题,如前面的答案所述:
if (!UserInputSplit[i].equalsIgnoreCase("the") || !!UserInputSplit[i].equalsIgnoreCase("the")) {
// Do something when neither are equal to the array element
}
但是,如果你有大量的项目,你可以考虑使用地图或一组:
// 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);
}
}
如果您要采用这种方法,当然您要么将其放入自己的类中,要么以某种方式将其加载一次,因为您不希望每次都设置一个巨大的地图。 / p>