我是java的新手,我正在尝试循环使用在main方法中使用增强的for循环创建的HashSet。我得到错误“无效”类型不允许在这里“并且我不太确定如何解决这个问题。我相信对于大多数人来说这似乎是一个简单的错误,但我非常喜欢初学者,所以一些帮助就像这个错误意味着什么以及如何解决它将非常感激。这是代码:
主要课程
package lab5;
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");
System.out.println("*****First Array list*****");
String[] firstWordArray = firstWordGroup.getWordArray();
for( String word : firstWordArray) {
System.out.println(word);
}
System.out.println("*****Second Array list*****");
String[] secondWordArray = secondWordGroup.getWordArray();
for( String word : secondWordArray) {
System.out.println(word);
}
secondWordGroup.getWordSet(secondWordGroup);
firstWordGroup.getWordSet(firstWordGroup);
for (WordGroup pp : secondWordGroup.getWordSet(secondWordGroup)) {
System.out.println(pp);
}
}
}
WordGroup类
package lab5;
import java.util.HashSet;
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 void 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);
}
}
答案 0 :(得分:0)
更改
public void getWordSet(WordGroup secondWordGroup) {
返回您正在构建的Set<String>
,例如
public Set<String> getWordSet(WordGroup secondWordGroup) {
和添加
return newHashSet;
到最后。然后,要使用for-each
循环对其进行迭代,它将为String
,因此您需要
for (String pp : secondWordGroup.getWordSet(secondWordGroup)) {
System.out.println(pp);
}