0

package SRM;

import java.util.*;

public class Coding {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    ArrayList<Integer> arr = new ArrayList<>(20);
    System.out.println("Enter the elements in the array: ");
    for (int i = 0; i < arr.size(); i++) {
        int a = sc.nextInt();
        arr.add(a);
    }

    for (Iterator<Integer> it = arr.iterator(); it.hasNext();) {
        System.out.println(it.next());
    }

}

}

For loop not executing. it prints "Enter the elements in the array: " and then terminates the program instead going getting input. Help me solve the issue

  • At the point you called `size()` the list hasn't had any elements added to it. So its size is zero. And therefore `0 < size` is `false` and the loop body doesn't execute. Note that `new ArrayList<>(20)` is NOT setting the size to 20. It is setting the *capacity* to 20. Read the javadocs for a better explanation. Or the duplink answers. – Stephen C Apr 15 '23 at 07:41

0 Answers0