0

I ran into an interesting situation when writing my program.

I am required to accept a word from the user to determine to continue the loop. Using .nextLine() did not allow the user to enter input and the program was aborted, but .next() ran perfectly fine.

I thought the difference was that .next() accepted input until the first space in the string while .nextLine() accepted the entire string.

Why does it matter if both are supposed to accept a user's input.. is there more to this?

.next() works perfectly fine for my program, but I'm curious for the future in case it happens again.

Thanks.

Jainish Kapadia
  • 2,535
  • 4
  • 14
  • 28
Alex
  • 11
  • 2
  • What was the last operation on the `Scanner` before you did the `nextLine` or `next`? Presumably something like `nextInt` that didn't pull off the newline character. – Dawood ibn Kareem Feb 28 '17 at 07:46
  • 2
    If you [edit] your question, add a short version of the code you wrote (a [mcve] is the best) and the input the user entered, we may be able to answer your question. – RealSkeptic Feb 28 '17 at 07:46
  • 1) I assume you're talking about `Scanner` - say so. 2) Format your wall of text using a) paragraphs and b) inline code (backticks). 3) Post your actual code in an [MCVE](https://stackoverflow.com/help/mcve) to demonstrate the problem. – Boris the Spider Feb 28 '17 at 07:46
  • you might like to see this. http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – sagar limbu Feb 28 '17 at 07:51
  • @Alex If you had simply done a search for "nextLine" you would have found 5,253 results. Most of them are duplicates of this exact same problem. – Patrick Parker Feb 28 '17 at 07:51
  • What was your input, what did you expect the result to be, and what was the result? What do you mean by "doesn't work"? What was the previous call, if any, of the Scanner? Could there be any whitespace somewhere? Without seeing the code and the inputs, everything we can say about it is pure guesswork – FredK Feb 28 '17 at 07:52

2 Answers2

1

I always prefer to read input using nextLine() and then parse the string.

Using next() will only return what comes before a space.nextLine() automatically moves the scanner down after returning the current line.

A useful tool for parsing data from nextLine() would be str.split("\\s+").

String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces

For more information regarding the Scanner class or String class refer to the following links.

Scanner :- http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

String :- http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Jainish Kapadia
  • 2,535
  • 4
  • 14
  • 28
0

maybe you need flush the in stream before use .nextLine() or you need use additional .nextLine() after .next() before the real .nextLine()

zzy
  • 119
  • 4