Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Read User Input in Java with Scanner (and the Leftover Enter Trap)

Scanner on System.in turns what the user types into Java values. Five small programs: read cups with nextInt, a full name with nextLine, the Enter that nextInt leaves behind, a coffee receipt, and every input type side by side.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Create a Scanner on System.in and read a number with nextInt
  • Pick the right method: nextInt, nextDouble, nextBoolean, next or nextLine
  • Fix the empty-string bug when nextLine follows nextInt
  • Recognise an InputMismatchException when the answer doesn't match the method

Before you start

  • Java strings and text blocks
  • Java methods and overloading

Until now every value was typed straight into the code, so a program always gave the same output. Think of an ATM that couldn't ask how much you want: it could only ever hand out one fixed amount. Scanner lets your program ask the user instead. It asks a question, waits while the cursor blinks, and moves on only when the user types an answer and presses Enter.

Three lines and the program listens

package org.studyeasy.s02l15;

import java.util.Scanner;

public class Ex01_ReadOneNumber {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("How many cups? ");
        int cups = keyboard.nextInt();
        System.out.println("Brewing " + cups + " cups.");
        keyboard.close();
    }
}
How many cups? 3
Brewing 3 cups.

(The 3 is what the user typed; IntelliJ shows typed text in green in the Run window.)

  • Scanner lives in java.util, so you import it. IntelliJ adds the import for you.
  • new Scanner(System.in) creates a Scanner called keyboard. System.in is the keyboard input.
  • print, not println, so the cursor stays on the question's line.
  • keyboard.nextInt() is where the program waits for a number and Enter.
The user types 3 and Enter on the keyboard. The keystrokes travel along System.in. Scanner's nextInt reads them and turns them into the number 3, which goes into the int variable cups. Keyboard'3' + Enter System.incarries keystrokes ScannernextInt() understands int cups= 3 System.in only carries the keys; Scanner turns them into a Java value.
From keystrokes to a Java value.

One whole line, spaces included

package org.studyeasy.s02l15;

import java.util.Scanner;

public class Ex02_ReadAWholeLine {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        // print, not println: the cursor waits on the same line as the question.
        System.out.print("Your full name: ");
        // nextLine() reads everything up to Enter, spaces included.
        String name = keyboard.nextLine();
        System.out.println("Welcome, " + name + "!");
        keyboard.close();
    }
}
Your full name: Mira Nair
Welcome, Mira Nair!

A name can have two words, so nextLine is the right choice. Swap it for next() and "Mira Nair" arrives as just "Mira".

Pick the method that matches the answer

MethodReadsUser typesJava gets
nextInt()a whole number2525
nextDouble()a decimal (a whole number works too)18.518.5
nextBoolean()only true or falsetruetrue
next()one wordMira Nair"Mira"
nextLine()the whole lineMira Nair"Mira Nair"

nextInt and nextLine are the two you'll use most.

nextInt() leaves the Enter behind

package org.studyeasy.s02l15;

import java.util.Scanner;

public class Ex03_TableAndName {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Table number: ");
        int table = keyboard.nextInt();
        // nextInt() leaves the Enter key behind, so read and drop it here.
        keyboard.nextLine();

        System.out.print("Customer name: ");
        String name = keyboard.nextLine();

        System.out.println("Table " + table + " -> " + name);
        keyboard.close();
    }
}
Table number: 7
Customer name: Anita Rao
Table 7 -> Anita Rao

The user typed 7, Enter, Anita Rao, Enter. nextInt takes the 7 and stops, but the first Enter is still waiting. The bare keyboard.nextLine() reads that Enter and drops it. Then the real nextLine gets "Anita Rao".

Delete the bare line and the name question reads the leftover Enter instead: it returns an empty String immediately and never stops for the name. This is the most common Scanner bug.

A receipt from three answers

package org.studyeasy.s02l15;

import java.util.Scanner;

public class Ex04_CoffeeReceipt {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        // The line goes first, so there is no leftover Enter to clean up.
        System.out.print("Customer name: ");
        String name = keyboard.nextLine();

        System.out.print("Cups: ");
        int cups = keyboard.nextInt();

        // The price can have decimals, so it is a double.
        System.out.print("Price per cup: ");
        double price = keyboard.nextDouble();

        System.out.println(name + " ordered " + cups + " cups");
        System.out.println("Total: " + (cups * price));
        keyboard.close();
    }
}
Customer name: Anita Rao
Cups: 3
Price per cup: 180.5
Anita Rao ordered 3 cups
Total: 541.5

Asking for the name first avoids the trap: nothing was read before it. The answers are real numbers now, so 3 x 180.5 = 541.5. Move the name question to the end, after nextDouble, and the receipt has no name.

All the types in one program

package org.studyeasy.s02l15;

import java.util.Scanner;

public class Ex05_InputTypes {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);

        System.out.print("Age: ");
        int age = keyboard.nextInt();
        System.out.print("Price: ");
        double price = keyboard.nextDouble();
        System.out.print("Member: ");
        boolean member = keyboard.nextBoolean();

        // next() takes one word and leaves the rest of the line behind.
        System.out.print("One word: ");
        String word = keyboard.next();
        keyboard.nextLine();

        System.out.print("Full line: ");
        String line = keyboard.nextLine();

        System.out.println("Age " + age + ", price " + price + ", member " + member);
        System.out.println("next() gave " + word);
        System.out.println("nextLine() gave " + line);
        keyboard.close();
    }
}
Age: 25
Price: 18.5
Member: true
One word: Mira Nair
Full line: Anita Rao
Age 25, price 18.5, member true
next() gave Mira
nextLine() gave Anita Rao

next() took only "Mira"; the rest of that line was still waiting, so a bare nextLine() drops it before the last question.

The answer must match the method

Type hello where nextInt expects a number and the program stops with an InputMismatchException. Scanner won't guess. nextInt wants a whole number, nextDouble a number, nextBoolean true or false.

Recap

  • new Scanner(System.in) reads the keyboard; import java.util.Scanner.
  • Ask with print, read with the method that matches the answer.
  • After nextInt, nextDouble or next, clear the leftover Enter with a bare nextLine() before reading a line.
  • A mismatched answer throws InputMismatchException.

Keep going in Java · 18 of 79

Previous
Java Scope, Code Blocks and the Call Stack
Next post
Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • Three lines and the program listens
  • One whole line, spaces included
  • Pick the method that matches the answer
  • nextInt() leaves the Enter behind
  • A receipt from three answers
  • All the types in one program
  • The answer must match the method
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.