Firstly, use one scanner rather than recreating a scanner every time. Also, your for loop loops one extra time.
Scanner sn = new Scanner(System.in);
System.out.println("Give me a size ");
int n = sn.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < n; i++){
System.out.println("Give me a number ");
int in = sn.nextInt();
list.add(in);
}
sn.close();
This works fine for me, at the end the List contains all the numbers I entered.
You can test it by printing the list:
System.out.println(list);
The problem with your old code is that when you use .close()
on the Scanner, it closes the underlying InputStream
, which is System.in
. If you close System.in
, you cannot use it again in the next Scanner. This is why using one Scanner fixes the issue.