我正在尝试在我的 Main 类中的 2 个词组上使用我的 WordGroup 类中的 getWordSet() 方法,并遍历返回的哈希集并打印出结果,但它甚至没有编译。我对我希望能做到的代码的尝试位于星号之间的主类的底部。有人可以帮我吗?编辑:我已经实施了建议的更改,如下面的代码所示,这导致了一个新问题-我希望两个词组进入同一个集合,但是当我尝试将 hashSTwo 更改为 hashSOne 以尝试将所有单词放入hashSOne 它不会编译。
import java.util.HashSet;
import java.util.HashMap;
public class Main{
public static void main(String[] args){
WordGroup wordgroupOne= new WordGroup ("You can discover more about a person in an hour of play than in a year of conversation");
WordGroup wordgroupTwo= new WordGroup ( "When you play play hard when you work dont play at all");
String[] quoteOne = wordgroupOne.getWordArray();
String[] quoteTwo = wordgroupTwo.getWordArray();
for (String words : quoteOne){
System.out.println(words);
}
for (String words : quoteTwo){
System.out.println(words);
}
**HashSet<String> hashSOne = wordgroupOne.getWordSet();
HashSet<String> hashSTwo = wordgroupTwo.getWordSet();
for (String set : hashSOne){
System.out.println(set);
}
for (String set : hashSTwo){
System.out.println(set);
}**
}
}
词组集:
import java.util.HashSet;
import java.util.HashMap;
public class WordGroup {
public String words;
public WordGroup (String getWords){
words = getWords.toLowerCase();
}
public String[] getWordArray(){
return words.split(" ");
}
public HashSet<String> getWordSet(){
HashSet<String> set = new HashSet<String>();
String[] p = getWordArray();
for (String items : p){
set.add(items);
}
System.out.println(set);
return set;
}
public HashMap<String, Integer> getWordCounts() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] q = getWordArray();
for (String stuff : q) {
Integer oldVal = map.get(stuff);
if (oldVal == null){
oldVal = 0;
}
map.put(stuff, oldVal+1);
}
System.out.println(map);
return map;
}
}