-1

I'd like to implement Scanner termination when input is complete. As a termination I choose blank line - just enter key. However for some reason (unknown to me) below implementation doesn't work. Do you have any idea why? Or maybe you know better solution?

Scanner scanner = new Scanner(System.in);
while (!scanner.nextLine().startsWith("\n")) {
     // code
}
// code after press just Enter

I tried also:

while (!scanner.nextLine().equals("\n")) 

... or:

while (scanner.nextLine().isEmpty())

Nothing works...

PS. Some of you may think that I duplicate this topic: How to terminate Scanner when input is complete?

However I do it on purpose, because I'm asking now about specific implementation, not a general Scanner termination.

Community
  • 1
  • 1
Rafal Iwaniak
  • 161
  • 1
  • 12

1 Answers1

1

You need to look for scanner.nextLine().length() == 0

Since \n is the line terminator, that's not going to be returned by the scanner, similar concept to parsing strings or using StringTokenizer. You just need to look for a zero-length string.

Scott Sosna
  • 1,443
  • 1
  • 8
  • 8
  • Your concept seems to be awesome! Thanks! However it doesn't give me any result, I don't know why. Any suggestions? Scanner scanner = new Scanner(System.in); while (scanner.nextLine().length() == 0) { //code } // this code doesn't work – Rafal Iwaniak Feb 12 '16 at 03:23
  • Your initial code wasn't assigning the line to a temporary variable before analyzing the empty line. By doing scanner.nextLine().length() in one call, you've consumed/analyzed/lost the line in a single step. I was just taking what you had, but wanted to see if you realized! :) – Scott Sosna Feb 12 '16 at 03:33
  • If I write smth like this below I will lose first line of input. int nextLine = scanner.nextLine().length(); while(nextLine == 0) { // code nextLine = scanner.nextLine().length(); } – Rafal Iwaniak Feb 12 '16 at 10:47
  • Look, if you want someone to do your homework, hire a tutor, it's a simple problem of always capturing the input prior to evaluating the data. – Scott Sosna Feb 13 '16 at 13:58