0

So, im new in Java and i would like to fill an ArrayList with integers form keyboard but after i run the code and give one number it gives me exceptions. What am i missing ?

import java.util.ArrayList; 
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int j=0,x=0;

ArrayList<Integer> numb = new ArrayList<Integer>(5);

    
    
    Scanner scanner = new Scanner(System.in);<br>
    System.out.println("Give numbers to the array:");<br>
    for(j=0;j<=5;j++)
    {
       
        System.out.println("Give the "+j+"st item of the list");
        x = scanner.nextInt();
        numb.set(j, x); 
    }
    System.out.println("\nThe array is:");
    for(Integer i:numb)
        System.out.println(i);
}

}

Ria.Np
  • 16
  • 3
  • 2
    Use `add(x)` instead of `set(j, x)`. You can't use `set` method on index which is not filled with data yet/"doesn't exist" (list is not an array). – Pshemo Oct 25 '21 at 06:37

0 Answers0