Tyranzor
Tyranzor

Reputation: 11

How to read last input to Scanner instance again?

How can I get the console scanner to use last input again? if I have something like y=scanner.nextInt(); and I want my next use of the scanner to use the same input from the previous line, how would I do that?

Upvotes: 1

Views: 3905

Answers (3)

Stephen C
Stephen C

Reputation: 719229

I want my next use of the scanner to use the same input from the previous line, how would I do that?

There is no way to make a Scanner do that. The Scanner API does not provide any methods for backtracking to a point before the last successful read operation. And trying to do this by "seeking" the underlying stream is unlikely to work either because of the scanner's internal buffering.

The best I can think of as a general solution is this:

Scanner scanner = new Scanner( ... )
while (scanner.hasNext()) {
    String line = scanner.nextLine();
    Scanner lineScanner = new Scanner(line);
    // read tokens from lineScanner
    // to "reset" to the start of the line, discard lineScanner
    // and create a new one.
}

Another approach might be just to save the things that you scanned, and do the resetting at a higher level. But that doesn't work if you need to rescan the line differently; e.g. using nextInt() calls instead of next() calls.

Upvotes: 2

Jennifer
Jennifer

Reputation: 210

    y=scanner.nextInt();//user inputs 5
     y=5;// You can reuse y
     x=y;// assign same input to another value

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

How can I get the console scanner to use last input again?

Don't. Save the last input in a variable or a collection and access it that way.

Upvotes: 1

Related Questions