How to use multiple Scanner objects on System.in?

What am I doing wrong?

Using multiple scanners on the same stream is the underlying problem. Scanners can (and will) consume the stream – this may (will) lead to unexpected side-effects. Best not to do it.

If the input is closed, then the input (but Strings have no close method) is closed for everyone – and that’s not much fun for anyone.

Edit: “Details” on why multiple scanners are bad: Do not create multiple buffered wrappers on an InputStream

…any buffered wrapper is unsafe; this condition is also exploitable if a Scanner is used instead…

See also Java code question … scanner related? which also talks about some approaches.

Leave a Comment