Scanner sc = new Scanner(System.in);
What do you do when you want to read an int in Java? You would probably write sc.nextInt().
And what about string? You would say sc.next() or sc.nextLine();
But if you are reading a line(series of strings) next, you would probably fall into a common pitfall where the line won't be read. If you use nextInt() or next() before nextLine(), the newline remains in the buffer.
Let me explain, suppose we read an integer and a line in the below format:
5
Hello World
You would probably write :
int num = sc.nextInt();
String s = sc.nextLine(); //the problem
String s here becomes empty because it actually reads the leftover newline(\n).
You example input actually looks like this internally in the buffer :
['5', '\n', 'H', 'e', 'l', 'l', 'o', '\n']
Since nextLine() reads till newline. So, what nextLine()does here is just read the first \n. So the string s becomes an empty string.
s = ""
What is the fix?
You need to consume the leftover line after 5. So what you have to do is simply move the nextLine() and read the line with nextLine() again.
int n = sc.nextInt();
sc.nextLine(); // removes leftover '\n'
String s = sc.nextLine();
So basically
nextInt() → reads number, leaves newline
next() → reads word, leaves newline
nextLine()→ reads everything until newline
That is why many programmers avoid Scanner entirely and use BufferedReader instead.
Top comments (0)