In Java, consider the following code snippet:Scanner sc = new Scanner(System.in); System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.print("Enter your full name: "); String name = sc.nextLine(); System.out.println("Age: " + age); System.out.println("Name: " + name);When ...Read more
1. next() Function: Reads the next token (word) from input. Delimiter: Stops reading when it encounters whitespace (space, tab, or newline). Ignores: Leading whitespace before the token. Use case: Good for reading single words. Example: Scanner sc = new Scanner(System.in); System.out.print("Enter yoRead more
1. next()
Function: Reads the next token (word) from input.
Delimiter: Stops reading when it encounters whitespace (space, tab, or newline).
Ignores: Leading whitespace before the token.
Use case: Good for reading single words.
Example:
Input:
Output:
👉 It only captures "Rahul"
because next()
stops at the first space.
2. nextLine()
Function: Reads the entire line of input (until Enter/
\n
).Delimiter: Stops only when the newline character is encountered.
Use case: Good for reading sentences or full lines with spaces.
Example:
Input:
Output:
👉 Here it captures the whole line, including spaces.
⚡ Key Differences Table
Feature | next() | nextLine() |
---|---|---|
Reads up to | Whitespace (space, tab, newline) | End of line (\n ) |
Can read spaces? | ❌ No (stops at space) | ✅ Yes (includes spaces) |
Best for | Single words/tokens | Full sentences / whole line |
The nextLine() method appears to skip input because after executing nextInt(), the newline character (\n) from pressing Enter is still left in the input buffer. When nextLine() is called immediately after, it reads this leftover newline character instead of waiting for new user input. As a result, iRead more
The
nextLine()
method appears to skip input because after executingnextInt()
, the newline character (\n
) from pressing Enter is still left in the input buffer.When
nextLine()
is called immediately after, it reads this leftover newline character instead of waiting for new user input. As a result, it returns an empty string and seems to “skip” the input.To fix the issue, insert an extra
sc.nextLine();
afternextInt()
to consume the leftover newline character.Scanner sc = new Scanner(System.in);
System.out.print(“Enter your age: “);
int age = sc.nextInt();
sc.nextLine(); // consume the leftover newline
System.out.print(“Enter your full name: “);
String name = sc.nextLine();
System.out.println(“Age: ” + age);
System.out.println(“Name: ” + name);
Now, if the input is:
20
Rahul Sharma
The output will be:
Age: 20
See lessName: Rahul Sharma