i have this method, and the idea is read from the console (keyboard) a sequence of int numbers and add all of them in an ArrayList, im using the class Scanner to read the nu
Your problem is here:
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
sn.close();
You're closing the current Scanner
, which will close the InputStream
used to read the data, which means your application won't accept any more input from user. That's why creating a new Scanner
that will read from System.in
won't work. Even if you create another kind of reader using System.in
won't work.
Usually, when dealing with System.in
you create a single reader (in this case, Scanner
) that will work for all the application. So, your code should look like this:
System.out.println("Give me a size ");
Scanner sn = new Scanner(System.in);
int n = sn.nextInt();
//sn.close();
List list = new ArrayList();
for (int i=0; i < n; ++i){
System.out.println("Give me a number ");
//Scanner sn2 = new Scanner(System.in);
int in = sn.nextInt();
list.add(in);
//sn2.close();
}