0

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();
}
asked Sep 27, 2016 at 0:38
1
  • 2
    Did you get a stack trace? What did it say? Commented Sep 27, 2016 at 0:41

2 Answers 2

1

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 + " ");
 }
}
answered Sep 27, 2016 at 0:42
Sign up to request clarification or add additional context in comments.

1 Comment

Simpler indeed! 1+
0

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;
}
answered Sep 27, 2016 at 0:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.