2013-07-31 62 views
-1

我有一個數組String[] questions={"adorable", "able", "adventurous"};,我還有一個數組t [],其中包含所有形容詞。我想在數組t中找到可愛,有能力和冒險的單詞。到目前爲止,我有這行代碼,但它似乎並沒有工作。有人可以幫幫我嗎?查找數組中的字符串是否存在於另一個數組中

String u = sn.nextLine(); 
    String[] t = u.split(" "); 
    for (y = 0; y <= question.length; y++) { 
     for (int w = 0; w < t.length; w++) { 
      if (t[w].equals(question[y])) { 
       System.out.print(t[w] + " "); 
       break; 
      } 
     } 
    } 
+1

外'for'中的終止條件不正確,並且會超出'question'數組的範圍:使用'<'不是'<='。 – hmjd

+2

只有當你對錶演完全無動於衷時,這才行。它可以通過一個與你的形容詞詞典的大小相稱的因子來加速,並且在那個代碼上的代碼更少。 –

+1

「似乎不起作用」如何? – Taylor

回答

1

務必:

for (int y = 0; y < question.length; y++) { 

} 

,而不是<=。事實上,您沒有question[question.length]元素的問題結果。

此外,我沒有看到你聲明y變量的位置。

更新:這裏有一個完整的示例:

String[] questions = {"adorable", "able", "adventurous"}; 
String u = "able adorable asd"; 
String[] t = u.split(" "); 
for (int y = 0; y < questions.length; y++) { 
    for (int w = 0; w < t.length; w++) { 
     if (t[w].equals(questions[y])) { 
      System.out.print(t[w] + " "); 
      break; 
     } 
    } 
} 

此打印:

adorable able 
+0

我刪除了等號但它仍然不會產生任何輸出:/ – user2610661

+0

請確保' u'變量不是空的。 –

+0

我試圖調試它,變量u不是空的。所以作爲字符串[]噸 – user2610661

4

這個怎麼樣:

Set<String> s1 = new HashSet<String>(Arrays.asList(t)); 
Set<String> s2 = new HashSet<String>(Arrays.asList(questions)); 

s1.retainAll(s2); 

現在s1包含t的所有字符串也出現在question


例如:

String[] t = "Hello, world! I am adventurous and adorable!".split("\\W+"); 
String[] questions = {"adorable", "able", "adventurous"}; 

Set<String> s1 = new HashSet<String>(Arrays.asList(t)); 
Set<String> s2 = new HashSet<String>(Arrays.asList(questions)); 

s1.retainAll(s2); 
System.out.println(s1); 
 
[adventurous, adorable] 
+0

實際上來自問題的字符串已經存在於t中。我只是試圖調試程序,看看它是否正常工作 – user2610661

+1

它的工作原理!非常感謝!我不能夠感謝你。 – user2610661

1
for(String question: questions){ 

    for(String word: t){ 

     if(question.equals(word)){ 

      //Do somethin 

     } 
    } 

} 
+0

我應用了你所建議的沒有給我任何輸出 – user2610661

0

另一種解決方案將是使用一個數據結構,例如一個ArrayList或鏈表,而不是陣列。

這樣,你可以調用contains()。

相關問題