我被分配创建一个列表列表,我应该能够使用“for each”类型的“for”循环遍历列表,而不是为迭代器构建一个构造函数。问题是,当我编写下面的代码时,我收到错误消息“只能遍历数组或 java.lang.Iterable 的实例”。这是代码:
public static void main(String[] args) {
GList<InnerList> list = new GList<InnerList>();
GList<InnerList> numList = new GList<InnerList>();
InnerList lst = new InnerList ();
Scanner sc = new Scanner(System.in);
String answer;
while (true){
System.out.println ("Do you want to create a list (y/n)? ");
answer = sc.next();
if (answer.equals("y")){
System.out.println("Enter the name of the list: ");
answer = sc.next();
lst.setName(answer);
if (list.isEmpty()== true){
list.insertFirstItem(lst);
}
else {
list.insertNext(lst);
}
}
while (true){
System.out.println("Do you want to enter a number (y/n)?");
answer = sc.next();
if (answer.equals("y")){
System.out.println("Enter Number: ");
answer = sc.next();
try {
int num1 = Integer.parseInt(answer);
lst.setInner(num1);
if (list.isEmpty() == true){
list.insertFirstItem(lst);
}
else {
list.insertNext(lst);
}
}
catch (NumberFormatException e){
System.out.println("You must enter an number! " + e);
sc.close();
}
}
return;
}
}
for (GList<InnerList> ilName : list){ //here are my error msgs. I also tried replacing GList<InnerList> with 'InnerList' and String.
for(GList<InnerList> ilInts : list){
System.out.println(ilName);
System.out.println(ilInts);
}
}
}
有人可以帮我理解为什么当集合应该是可迭代的时 GList 不被视为 java.lang.iterable 的实例吗?
谢谢你。