我已經被賦予創建列表的列表,我應該能夠遍歷列表使用'for each'類型的'for'循環,與爲Iterator構建構造函數。問題是,當我下面的代碼,我得到錯誤味精「只能遍歷數組或java.lang.Iterable的實例」。下面是代碼:如何迭代通用列表使用for Each類型For循環
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);
}
}
}
有人可以幫助我瞭解爲什麼鏈表本身不被認爲java.lang.iterable的實例時集應迭代?
謝謝。
什麼錯誤它顯示? – 2013-02-23 17:11:40
原始文章中的錯誤是「」只能迭代一個數組或java.lang.Iterable的實例「 – Chris 2013-02-23 17:14:24