1

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?

RGO
  • 4,586
  • 3
  • 26
  • 40

2 Answers2

2

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.

tckmn
  • 57,719
  • 27
  • 114
  • 156
0

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

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • It doesn't work for me. Could you put a working code here, please? – RGO Jan 19 '13 at 01:55
  • 2
    @Reza: I'm not going to write your code for you. I suggest referring to a book on Java, or perhaps a tutorial, e.g. http://docs.oracle.com/javase/tutorial/essential/io/scanning.html. – Oliver Charlesworth Jan 19 '13 at 01:56
  • There is no mentioning of such a problem there. This is why I asked it here. `hasNextInt` cannot solve the issue (I couldn't. Please see the update) – RGO Jan 19 '13 at 02:00
  • @Reza: There's a working example of how to use `hasNext` and `next`. You should use that pattern. – Oliver Charlesworth Jan 19 '13 at 02:02