CodeBlanks Logo Icon CodeBlanks

nextInt and nextLine

Learn type conversion with nextInt() and nextLine().

Read numbers with nextInt

nextInt() reads an integer from the console. nextDouble() is used for decimal numbers. These methods read the number but leave the trailing \n in the buffer.

Scanner input = new Scanner(System.in);
System.out.print("Age: ");
int age = input.nextInt();
System.out.println("Your age " + age);

If you call nextLine() right after reading a number, you get an empty string; the leftover \n is consumed at once. This trap is covered in the next card. For now, grasp the basics of reading numbers.

The nextInt and nextLine trap

nextInt() reads the number but leaves the trailing \n. If you then call nextLine(), the leftover \n is consumed at once and you get an empty string. The fix: after reading a number, call an empty nextLine() to clear the rest of the line.

int age = input.nextInt();
input.nextLine(); // clear leftover \n
String name = input.nextLine();

This pattern is a common mistake. Whenever you read text after a number, always insert a nextLine() in between. That way the next nextLine() reads the real user input.

Practice Age and name together

Read the user's age (nextInt) first, then their name (nextLine). Remember to clear the leftover line after the number. Print Hello <name>, you are <age>. The user will type 30 then Mehmet.

Starter code

Main.java
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    // read age, clear leftover line, read name, greet
  }
}

Sample solution

Main.java
System.out.print("Yaş: ");
int age = input.nextInt();
input.nextLine();
System.out.print("Ad: ");
String name = input.nextLine();
System.out.println("Merhaba, " + name + ", " + age + " yaşındasın");

Expected output

Yaş: Ad: Merhaba, Mehmet, 30 yaşındasın

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Read the age

Question
System.out.print("Age: ");
int age = input.____();
System.out.println(age);
Answer
System.out.print("Age: ");
int age = input.nextInt();
System.out.println(age);

Explanation: nextInt() reads an integer.

2 What is the value of name after this code? int n = input.nextInt(); String name = input.nextLine(); (The user types 25 and presses Enter, then types Ayşe and presses Enter.)

  • Ayşe
  • 25
  • 25Ayşe
  • Empty string ("") Correct answer

Explanation: nextInt reads 25 but leaves \n; nextLine consumes the leftover \n at once and returns an empty string.

3 Match each read method to its type

Term Meaning
nextInt() int
nextDouble() double
nextLine() String
nextBoolean() boolean

All lessons in Beginner