迭代器有问题。程序接受元素,存储它。但在显示时,它崩溃了。为什么会发生这种情况?那么,显示元素的正确方式是什么呢?
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num;
String dec;
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
while(true){
ArrayList<Integer> al2 = new ArrayList<Integer>();
while (true){
System.out.print("Enter a number to store in inner arraylist or zero to exit inner arraylist:t");
num = sc.nextInt();
if (num!=0){
al2.add(num);
}else{
break;
}
}
al.add(al2);
System.out.print("Exit(Y/y):t");
dec=sc.next();
if(dec.equals("Y") || dec.equals("y")){
Iterator<ArrayList<Integer>> it = al.iterator();
Iterator<Integer> it2 = al2.iterator();
while(it.hasNext()){
while(it2.hasNext()){
System.out.print(it2.next() + " ");
}
System.out.println();
}
break;
}
}
sc.close();
}
问题是当你这样做时
Iterator<Integer> it2 = al2.iterator();
al2
仍然指向最后一个值
for
语法
for (ArrayList<Integer> outer : al) {
for (ArrayList<Integer> inner : outer) {
System.out.print(inner + " ");
}
}
需要为外部循环的每次迭代创建内部迭代器。您不能重用它,因为它绑定到单个数组列表,并且当外部循环获取下一个迭代器时,原始it2是无用的。同样,在外部循环中创建它。比如:
if(dec.equals("Y") || dec.equals("y")){
Iterator<ArrayList<Integer>> it = al.iterator();
// Iterator<Integer> it2 = al2.iterator();
while(it.hasNext()){
ArrayList<Integer> myList = it.next();
Iterator<Integer> it2 = myList.iterator();
while(it2.hasNext()){
System.out.print(it2.next() + " ");
}
System.out.println();
}
break;
}