zcahfg2
zcahfg2

Reputation: 891

Java Scanner useDelimiter unexpected result

We get 'ab' as console output when we pass the string to the scanner like this:

 public static void main(String []args){
    Scanner sc = new Scanner("a///b");
    sc.useDelimiter("/");

    System.out.print(sc.next());    
    System.out.print(sc.next());    
    System.out.print(sc.next());    
    System.out.print(sc.next());    
    sc.close();
 }

But if we change the scanner line to

Scanner sc = new Scanner(System.in);

and pass in the same string a///b

The console output 'a' only. The console expects to input another / to output the same value.

Why do they work differently?

Upvotes: 4

Views: 136

Answers (1)

rgettman
rgettman

Reputation: 178293

A Scanner on a String has reached the end of its input when it reads the 'b' character. But when you use a Scanner on System.in, the stream hasn't ended yet; you can still type in more input after a newline character.

If you type in a///b Enter, you can still type in another delimiter character / that will finally let the Scanner know that the token is finished. If you type in foo/, then the next token is "b\nfoo", illustrating that the Scanner knows that b is just the start of the next token, which isn't finished until another / arrives on the stream.

Here I've placed double-quotes around all output to display each token found, even if empty.

a///b    <- input; token starting with "b" is unfinished
"a"      <- output
""       <- output
""       <- output
foo/     <- input
"b       <- output
foo"     <- output

Upvotes: 2

Related Questions