-1

I am reading a number, then a string and then comparing the string. This works fine:

    int num = sc.nextInt();
    String S = sc.next();
    if (S.equals("TEST")){
    //do something
    }

On giving i/p say 5 TEST, the program enters the if part.

But if I use .nextLine() instead, ie,

    int num = sc.nextInt();
    String S = sc.nextLine();
    if (S.equals("TEST")){
    //do something
    }

It doesn't work. For the same input(5 TEST) it won't execute the if part.

I know .next() reads up till the first whitespace and .nextLine() reads up till it encounters "\n". Here both of them are returning the same string, so what's going wrong here?

EDIT: Found out that .nextLine() was reading the String alongwith the preceding whitespace. Why? Does the .nextInt() function return the cursor to the point before it encounters the delimiter?

Little_idiot
  • 115
  • 7
  • Have you tried printing out `S` to see what the value actually is? – Dan W May 15 '19 at 15:46
  • @DanW yes, .nextLine() gives " S" (alongwith the preceding whitespace) – Little_idiot May 15 '19 at 15:49
  • 1
    Possibly related: [What's the difference between next() and nextLine() methods from Scanner class?](https://stackoverflow.com/q/22458575) – Pshemo May 15 '19 at 15:53
  • In short, `next()` returns next *token* without *delimiters* which by default is one-or-more-whitespaces (`\\s+`) while `nextLine()` doesn't care about delimiters set up for scanner, it sees as delimiter only line separator, so whitespace before `_TEST` is non-delimiter for it, so it is included as part of result. – Pshemo May 15 '19 at 15:57
  • The question in your 'edit' is answered by reading the javadoc for Scanner. – Roddy of the Frozen Peas May 15 '19 at 16:06
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Progman May 15 '19 at 18:29
  • @Progman That is not what this question is about. Here `nextLine()` doesn't hold empty value but `(space)TEST` which is causing `(S.equals("TEST")` to fail. – Pshemo May 15 '19 at 20:05

1 Answers1

0

Is simple: next() return the next token using a delimiter pattern, which by default matches whitespace (so white space are eliminated because are separator) instead nextLine() read from the current cursor position to the end of the line.

christian mini
  • 1,520
  • 18
  • 36