對於我的任務,我一直要求出示以下:如何使用增強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) –