例如:
if(!UserInputSplit[i].equalsIgnoreCase("the" || "an")
产生一个语法错误。这有什么办法?
您需要明确地与每个字符串进行比较。
例子:
if(!UserInputSplit[i].equalsIgnoreCase("the") || !UserInputSplit[i].equalsIgnoreCase("an"))
使用一系列 || 如果您有一小部分要比较的项目,那很好,如较早的答案中所述:
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);
}
}
如果您采用这种方法,您当然希望将其放入自己的类中,或者以某种方式将其加载一次,因为您不希望每次都设置一个巨大的地图。