0

How to properly use the next() and nextLine() methods when inputting String values?

Sometimes the console doesn't execute the String input statements and it also occurs when I use loops. I think that the next() and nextLine() methods are used improperly.

7th Nov 2018, 10:28 PM
Mr.Gameplay Network
Mr.Gameplay Network - avatar
2 odpowiedzi
+ 8
If you write "Hello World" in the console: Using next() you will get the word "Hello" as the input value and you won't get the next word. Use nextLine() instead, you will get the whole line ("Hello World" in this case) you have written, since it will read the full line and will move on to the next line. https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
9th Nov 2018, 1:41 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 2
Its a common problem with nextLine You shouldnt mix nextLine() with next() or nextInt() etc Because those input left an unused input in buffer, what did they leave ? Mostly a new line character and some other in case of next(), yes when you pressed enter the new line are actually there but they not take it and leave it there. But nextLine() see the new line character in the buffer as teminating input, newLine normally will take every character before new line, but if its found a new Line in the buffer it'll think that "oh that the end" and put everything else before the new line which is most of times, nothing.
7th Nov 2018, 11:33 PM
Taste
Taste - avatar