2013-07-31 61 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()。

相关问题