对于我的任务,我一直要求出示以下:如何使用增强for循环遍历另一个方法中的HashSet?
- 创建
HashMap<String,Integer>
- 遍历由
getWordArray()
返回的所有单词,并把每个单词到HashMap
用的次数就发生 - 返回
HashMap<String, Integer>
我已经创建了内部调用getWordArray()
另一种方法HashSet的,但我struggli ng找出如何使它for循环迭代通过getWordSet()
方法而不会出现错误“non-static
方法不能从静态上下文中引用”。当我返回创建的HashSet
字符串时,出现错误“不兼容的类型:
HashMap<String, Integer>
无法转换为字符串”。
下面是代码:
WordGroup类
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
public class WordGroup {
String word;
//Creates constructor which stores a string value in variable "word" and converts this into lower case using the lower case method.
public WordGroup(String aString) {
this.word = aString.toLowerCase();
}
public String[] getWordArray() {
String[] wordArray = word.split("-");
return wordArray;
}
public Set<String> getWordSet(WordGroup secondWordGroup) {
HashSet<String> newHashSet = new HashSet<>();
for (String word : secondWordGroup.getWordArray())
newHashSet.add(word);
for (String word : this.getWordArray())
newHashSet.add(word);
System.out.println(newHashSet);
return newHashSet;
}
public String getWordCounts()
{
HashMap<String, Integer> myHashMap=new HashMap<String, Integer>();
int loopcounter = 0;
for (WordGroup it : WordGroup.getWordArray())
loopcounter = loopcounter +1;
myHashMap.add(it);
return myHashMap;
}
}
主类
public class Main{
public static void main (String[] args) {
WordGroup firstWordGroup = new WordGroup("You-can-discover-more-about-a-person-in-an-hour-of-plau-tban-in-a-year-of-conversation");
WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");
}
我有两个主要的疑问:
- 如何正确迭代getWordArray方法?
- 如何返回数据类型的HashMap而不是String?
我看不到我的WordGroup类正在使用的任何静态方法所以很明显我的静态一些误解的地方,我知道了第二个错误,我只是没有就如何解决它太肯定。
在此先感谢。
编辑:
public Set<String> getWordCounts(WordGroup secondWordGroup)
{
HashMap<String,Integer> myMap;
if (myMap.keySet().contains(getWordArray[i]))
{
myMap.get(getWordArray[i]) +1;
}
else
{
myMap.put(getWordArray[i],1);
}
return myMap;
}
我不知道如果是做正确的,但有多个错误:我一直在使用这个if语句试过吗?
对于与静态方法有关的错误,您可以使该方法非静态? 对于与不兼容类型相关的错误,我相信你应该创建一个HashMap而不是HashSet 。 –
ritratt
这就是我感到困惑的地方,我根本没有在WordGroup类中看到static这个词,所以我认为一切都是非静态的? – Alan
我想你想[这](http://stackoverflow.com/questions/19896467/putting-words-from-an-array-into-a-hashmap-and-a-hashset) –