2013-02-10 34 views

回答

5

您需要明確地比較每個字符串。

實施例:

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

將開關語句爲此工作? – EAKAE 2013-02-10 04:35:34

+0

您只能在原始類型(即不是字符串)上進行「切換」。 – Th3Cuber 2013-02-10 04:36:27

+3

@EAKAE:如果Java是1.7或更高版本,Swithc可以工作。 – kosa 2013-02-10 04:37:09

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); 
    } 
} 

如果你去這個方法,當然你想要麼把它放進自己的類或以某種方式把它加載一次,因爲你止跌」我想每次都要創建一個巨大的地圖。

相關問題