[英]Iterating through a hashset and printing the result
我試圖在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;
}
}
您不應該在quoteOne
上使用getWordSet()
,因為它是String[]
並且沒有這種方法。 您可能想在WordGroup
類型的wordgroupOne
上使用它。 quoteTwo
。
另外,如果可能的話,您應該更喜歡在接口上進行編程,而不是在實際的類上進行編程,因此可以將方法更改為返回Set
而不是HashSet
。
如何將兩個結果放入相同的哈希集中? 我嘗試將它們都更改為hashSOne,它只是在我的第一個哈希集上寫了第二個
你可能做到了
hashSOne = hashSTwo;
這只是使hashSOne
引用使用來自hashSTwo
引用的集合。
如果要創建將包含兩個集合中所有項目的新集合,則可以按照以下方式進行操作
//lets create Set with elements from first set
Set<String> allElements = new HashSet<>(hashSOne);
//now lets add all elements from second set
allElements.addAll(hashSTwo);//this will not add duplicates
也許從查看該getWordArray()方法開始。 我懷疑您的正則表達式有點閃避。 請參閱此SO鏈接以獲取空格拆分正則表達式。
對於以后的帖子,您絕對應該更具體地指出錯誤是什么。 沒有編譯器的幫助,很難找到錯誤所在。
HashSet<String> hashSOne = quoteOne.getWordSet();
HashSet<String> hashSTwo = quoteTwo.getWordSet();
應該
HashSet<String> hashSOne = wordgroupOne.getWordSet();
HashSet<String> hashSTwo = wordgroupTwo.getWordSet();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.