🧠 Understanding Scanner Input in Java: The Confusion Between next() and nextLine()

ProdDevTalesProdDevTales
2 min read

When you're starting with Java and working with user inputs using the Scanner class, you might run into a common (and very confusing!) issue when reading both tokens and full lines. Let’s break it down step by step so you can fully understand what’s happening.


🔍 The Issue I Faced

While I was learning how to take inputs using Scanner, I ran into a weird problem.

I was trying to take both a character (or number) and a string as input. But whenever I tried to take a string input after a character or number, it seemed like Java was skipping the string input completely.

Here’s what I mean:

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();      // Token-based input
String name = sc.nextLine(); // Line-based input
System.out.println("Name: " + name);

Now if I input:

10
John

It prints:

Name:

Wait… where did “John” go? 🤔


🧪 What’s Going On?

The problem is that there are two different types of input methods in Scanner:

1. Token-based inputs

These include:

  • next()

  • nextInt()

  • nextDouble(), etc.

These methods read input only up to the first whitespace (space, tab, or newline). They leave the rest of the line (including the newline \n) behind.

2. Line-based input

  • nextLine()

This reads everything on the line, including spaces, until it hits a newline character (\n).


🎯 Why It Skips the String?

So, in our case:

  1. sc.nextInt() reads the number (10), but leaves the newline (\n) in the input buffer.

  2. Then, sc.nextLine() comes in and sees the leftover \n, thinks "Oh hey, here's the end of the line!", and returns an empty string.


✅ How to Fix It?

Simple! After using a token-based method like nextInt() or next(), just add a dummy nextLine() to consume the leftover newline.

Here’s the corrected version:

Scanner sc = new Scanner(System.in);
int num = sc.nextInt();      // Reads number
sc.nextLine();               // Consumes leftover newline
String name = sc.nextLine(); // Now reads the full line
System.out.println("Name: " + name);

Now input:

10
John

Output:

Name: John

Problem solved! 🎉


✍️ Summary

  • next(), nextInt(), etc. are token-based and don't consume the newline.

  • nextLine() is line-based and consumes everything till the newline.

  • Always add a nextLine() after a token-based input if you plan to use nextLine() afterward.


💡 Pro Tip for Beginners

If you're reading mixed inputs (numbers and strings), always think about whether you want to grab a word/token or a full line. And don’t forget the sneaky newline issue! 😄

0
Subscribe to my newsletter

Read articles from ProdDevTales directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ProdDevTales
ProdDevTales