Question

This simple piece of code:

import java.util.Scanner;

public class TestScanner {

    public static void main(String[] args){

        Scanner sc1 = new Scanner(System.in);
        int number1 = sc1.nextInt();
        sc1.close();

        Scanner sc2 = new Scanner(System.in);
        int number2 = sc2.nextInt();
        sc2.close();
    }

}

always gives me this error:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:838)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at mainpkg.TestScanner.main(TestScanner.java:14)

This one doesn't work either. This time it falls into a never-ending loop!

import java.util.Scanner;

public class TestScanner {

    public static void main(String[] args){

        Scanner sc1 = new Scanner(System.in);
        int number1 = sc1.nextInt();
        sc1.close();

        Scanner sc2 = new Scanner(System.in);
        while(!sc2.hasNextInt())
            ;
        int number2 = sc2.nextInt();
        sc2.close();
    }

}

Why?

Was it helpful?

Solution

The problem is that sc1.close(); closes the underlying stream. The second time, you're trying to read from a closed stream, so it obviously fails.

OTHER TIPS

You should be checking each time with hasNextInt, rather than just assuming that there's more to read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top