As a programming language with its fair share of quirks, one of the many things a new Java programmer will run into is the issue of their Scanner.nextLine()
calls being ignored. Consider the following Java code:
JavaNextLineProblem.java
import java.util.Scanner; public class JavaNextLineProblem { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter their name. System.out.print("Enter your name: "); String name = input.nextLine(); // Prompt the user to enter their age. System.out.print("Enter your age: "); int age = input.nextInt(); // Prompt the user to enter a description. System.out.print("Describe yourself in a sentence: "); String description = input.nextLine(); // Prompt the user to enter a message. System.out.print("Enter a message: "); String message = input.nextLine(); } }
This is the desired result (user input coloured in green):
Enter your name: John Enter your age: 21 Describe yourself in a sentence: I am awesome. Enter a message: Hello world!
However, this is what you actually get:
Enter your name: John Enter your age: 21 Describe yourself in a sentence: Enter a message: Hello world!
The program skips over the collection of input for the Describe yourself in a sentence prompt, and goes straight into collecting the input for the Enter a message prompt. What’s going on?
Continue reading