Q: Help understanding closing Scanner

This is my working code.

public static void play() {

    Scanner myScanner = new Scanner(System.in);
    Scanner myOtherScanner = new Scanner(System.in);

    while (!endCondition()) {
        //stuff
        shoot(myScanner);
    }

    keepPlaying(myOtherScanner);

    myScanner.close();
    myOtherScanner.close();
}

Method receiving myScanner:

static void shoot(Scanner sc) {
    int bullet;
    //Stuff

    bullet = Integer.parseInt(sc.next());

    //More stuff
}

Method receiving myOtherScanner:

static void keepPlaying(Scanner myOtherScanner) {

    //Stuff

    int option = Integer.parseInt(myOtherScanner.next());

    //More stuff
}

Now what I don't understand:

If I close myScanner before calling keepPlaying(myOtherScanner), myOtherScanner.next() will throw:

NoSuchElementException

From what I've found it seems that closing a single Scanner closes System.in. Is that correct?

What is a good way to go around it? Closing only at the very end?

Is it better to use a single Scanner?

Do I use the Scanners as global class elements?

Do I just not close the Scanners?

Upvotes: 0

Views: 73

Answers (2)

Roshana Pitigala
Roshana Pitigala

Reputation: 8806

A work around for this is to create your own java.io.FilterInputStream.

Scanner myScanner = new Scanner(new FilterInputStream(System.in) {
    public void close() throws IOException {
    }
});

Now when you call,

myScanner.close();

it closes only your FilterInputStream leaving the System.in open (Source).


Or you can just use a single Scanner as long as your application is single threaded.

Upvotes: 1

Tarun
Tarun

Reputation: 986

When you call .close() on any resource like you are calling myScanner.close(); it will close the resource and in stream as well.

Once the input stream is closed it cannot be reopened(as per javadoc) and since you are using same System.in stream in both scanners, once it is closed by myscanner it is not available for myOtherScanner, therefore it is giving Exception.

Upvotes: 0

Related Questions