1

I am using scanner to get input of a String.My code is as below

String s=scan.next();
if(scan.hasNext()){
    s +=scan.nextLine();
}

But the problem is it is not reading the white spaces in the beginning.

Example

Input            :    Hello   World

Output should be :    Hello   World

Output is        :Hello   World

Please clarify what is the mistake and help me rectify.

Pshemo
  • 113,402
  • 22
  • 170
  • 242

2 Answers2

1

next() method is used to let us get next word (token) without preceding delimiters. Default delimiter used by Scanner is one or more whitespace so it was ignored by design.

If you want s to hold entire line (or rest of current line) including delimiters then skip next() and use only nextLine().

String s = scan.hasNextLine() ? scan.nextLine() : "";

But be careful about problem which is often faced when we mix next and nextLine described in: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

Pshemo
  • 113,402
  • 22
  • 170
  • 242
0

Read the scanner documentation

scan.next() breaks the input into tokens based on white space.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Try this:

String s="";
        if(scan.hasNext()){
        s +=scan.nextLine();
    }
Eduardo Dennis
  • 12,511
  • 11
  • 72
  • 102