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

4 回答 4

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);
[冒险,可爱]
于 2013-07-31T14:38:02.217 回答
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
于 2013-07-31T14:32:25.373 回答
1
for(String question: questions){

    for(String word: t){

        if(question.equals(word)){

             //Do somethin

        }
    }

}
于 2013-07-31T14:38:18.140 回答
0

另一种解决方案是使用数据结构,例如 ArrayList 或 LinkedList,而不是数组。

这样,您只需调用 contains()。

于 2013-07-31T15:21:59.220 回答