【发布时间】:2013-11-22 16:06:30
【问题描述】:
我正在使用 blueJ 进行编码,而我正在尝试做的是:
1.a) 在WordGroup 中创建一个getWordSet() 方法:
- 将另一个
WordGroup对象作为参数 - 创建
a HashSet<String> - 使用两个for循环将所有单词和参数
WordGroup放入HashSet - 返回
HashSet<String>
1.b) 在main 方法中:
- 使用
getWordSet()方法,使用两个WordGroups - 迭代或循环返回的
HashSet并从中打印单词
2.a) 在WordGroup 中创建一个名为getWordCounts() 的方法:
- 创建一个
HashMap<String, Integer> - 循环遍历
getWordArray()返回的所有单词,并将每个单词及其出现次数放入HashMap中 - 返回
HashMap<String, Integer>
2.b) 在main 方法中:
- 在两个
WordGroups 上拨打getWordCounts() - 使用
keySet()检索键集(映射的字符串部分) - 循环遍历该集合并打印出
WordGroups 的单词及其计数 - 使用
getWordSet()方法将WordGroups 中的所有单词组成完整的集合 - 循环遍历新的
HashSet以打印所有单词的完整列表,其中包含每个HashMaps 的总计数
到目前为止我的代码:
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);
}
}
}
WordGroup 类:
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>();
for (String words : quoteOne){
words.add(word);
}
return words;
}
public HashMap<String, Integer> getWordCounts() {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String words : words) {
words.add(word);
}
return HashMap<String, Integer>;
}
}
我已经走到了这一步,现在我被困住了。我无法弄清楚如何将 teh 数组中的单词放入 hashset 和 hashmap 以及如何以所需的形式返回它们。 p.s.对奇怪的问题布局感到抱歉-如果字符串不是代码格式,则字符串在 hashset 后一直消失)
【问题讨论】:
-
我什至不确定这段代码是否可以编译。 quoteOne 在哪里定义? getWordCounts 方法的返回值也不正确。
标签: java arrays hashmap hashset