0

I am getting a weird runtime error while trying to input a String.

I input the String using Scanner Class by using the nextLine() function :

System.out.println("Enter a String.");
String str = in.nextLine();

I put random printing messages in between the lines of my code to see why this is happening and to know the origin of error. After eliminating every possible source of error, I have finally come to the conclusion that the program automatically accepts an empty String.

I looked up the program I was working on the internet and what i found was that when I write this, :

System.out.println("Enter a String.");
in.nextLine();
String str = in.nextLine();

everything seems to work properly. The program inputs the String properly without any problem.

Please note that I am just a beginner in Java. In my (very little) experience, nextLine() function never gave any such error. Never. It always worked properly. But this time, I am very confused. Please help me out.

EDIT : Also, my program compiled successfullly without any compile errors.

  • 1
    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) – GBlodgett Dec 27 '18 at 14:51
  • 1
    You must have a call to `nextInt()` or `next()` in your code. These do not consume the newline, and when you call `nextLine()` it captures an empty `String` – GBlodgett Dec 27 '18 at 14:52
  • @GBlodgett I am sorry but I do not know what is a "newline". Can you please explain in simpler terms? –  Dec 27 '18 at 14:53
  • @ND_QUNAUM a "newline" is when you press "enter" – Federico klez Culloca Dec 27 '18 at 14:54
  • Anyway, please post a bit more context to your code. Ideally you should post a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) – Federico klez Culloca Dec 27 '18 at 14:56
  • nextLine() takes empty string. – Vishwa Ratna Dec 27 '18 at 14:57
  • @ND_QUNAUM When you enter in the input to the console, and then hit enter, that is a newline. `nextInt()` and `next()` do not consume the newline, so all thats left is an empty `String` and the newline, so `nextLine()` captures an empty `String` – GBlodgett Dec 27 '18 at 15:05
  • Please read the thread I linked to you; it explains it very nicely – GBlodgett Dec 27 '18 at 15:05
  • @GBlodgett Thank you very much.I got my problem solved. –  Dec 27 '18 at 15:50

0 Answers0