There is a problem with the iterator. The program accepts the elements, store it. but upon displaying, it crashes. Why does this happens? And, what is the correct way of displaying the elements?
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();
}
-
2Did you get a stack trace? What did it say?shmosel– shmosel2016年09月27日 00:41:11 +00:00Commented Sep 27, 2016 at 0:41
2 Answers 2
The problem is that when you do
Iterator<Integer> it2 = al2.iterator();
al2
is still pointing to the last value
A simpler way would be to use this for
syntax
for (ArrayList<Integer> outer : al) {
for (ArrayList<Integer> inner : outer) {
System.out.print(inner + " ");
}
}
1 Comment
You need to create your inner iterator with each iteration of the outer loop. You can't reuse it since it's tied to the individual array list, and when the outer loop fetches the next iterator, the original it2 is useless. Again, create it within the outer loop. Something like:
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;
}