Question

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 numbers but in the for loop doesnt works, it throws "java.util.NoSuchElementException".

public static int mayorNumberSecuence(){
        System.out.println("Give me a size ");
        Scanner sn = new Scanner(System.in);
        int n = sn.nextInt();
        sn.close();
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<= n; ++i){
            System.out.println("Give me a number ");
            Scanner sn2 = new Scanner(System.in);
            int in = sn2.nextInt();
            list.add(in);
            sn2.close();
        }
Was it helpful?

Solution 2

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.

OTHER TIPS

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<Integer> list = new ArrayList<Integer>();
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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top