Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
1. Java Fundamentals
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

7. User Input via Scanner

Interacting with users by reading text from the command line.

Java Programming: From Zero to Enterprise
1. Java Fundamentals
February 22, 2026
125
A

[!NOTE] A program isn't very interactive if it only talks to itself. The Scanner class allows your application to pause execution and wait for the user to type something on their keyboard.

Importing and Setting Up Scanner

The Scanner class is not loaded by default to save memory. You must actively import it from the java.util package.

import java.util.Scanner;  // Import the Scanner class

public class Main {
  public static void main(String[] args) {
    // 1. Create a Scanner object hooked up to the System Input stream (keyboard)
    Scanner myObj = new Scanner(System.in);
    
    System.out.println("Enter username:");

    // 2. Pause the program and wait for the user to hit Enter
    String userName = myObj.nextLine(); 
    
    System.out.println("Welcome, " + userName + "!");
    
    // 3. Close the scanner when done!
    myObj.close();
  }
}

[!CAUTION] Always remember to call .close() on your Scanner when your program finishes. Leaving input streams open can cause resource memory leaks.

Reading Different Data Types

The Scanner has different methods corresponding to the primitive data type you want to read.

Method Description
.nextLine() Reads a String value (the entire line including spaces).
.nextInt() Reads an int value.
.nextDouble() Reads a double value.
.nextBoolean() Reads a boolean value.

The "Scanner Bug"

  • Newline Artifacts

A very common trap for beginners: If you read an integer, and then immediately try to read a string, it will skip the string! Why? Because nextInt() only reads the number, leaving the "Enter" keypress (newline character) sitting in the buffer. The subsequent nextLine() immediately swallows that newline and finishes.

The Fix: Manually fire a blank nextLine() after reading numbers to clear the buffer.

System.out.println("Enter age:");
int age = scanner.nextInt();

// The Fix! Clear out the leftover 'Enter' key press
scanner.nextLine(); 

System.out.println("Enter name:");
String name = scanner.nextLine(); 

Building Input That Does Not Break Easily

User input is messy. People type spaces, wrong numbers, blank lines, and unexpected words. A beginner program can assume perfect input, but useful programs validate before using input.

Checking Before Reading a Number

Scanner scanner = new Scanner(System.in);

System.out.println("Enter age:");
if (scanner.hasNextInt()) {
    int age = scanner.nextInt();
    System.out.println("Age: " + age);
} else {
    System.out.println("Please enter a valid whole number.");
}

Methods like hasNextInt() let you check whether the next input can be parsed safely. This prevents InputMismatchException.

A Simple Menu Loop

Scanner scanner = new Scanner(System.in);
int choice;

do {
    System.out.println("1. Start");
    System.out.println("2. Help");
    System.out.println("0. Exit");
    choice = scanner.nextInt();
} while (choice != 0);

Common Mistakes

  • Mixing nextInt() and nextLine() without clearing the leftover newline.
  • Closing a Scanner around System.in too early in larger programs.
  • Assuming every user will enter the correct data type.
  • Not showing clear prompts before waiting for input.

Mini Practice

Build a tiny marks calculator. Ask for a name and three marks. Validate numeric input, calculate the average, and print whether the student passed.

Practice Lab: Interactive Marks Calculator

Use Scanner to make your program respond to real input.

  1. Ask for the student's name.
  2. Ask for three marks.
  3. Calculate the average.
  4. Print whether the student passed.
  5. Handle the newline issue after numeric input.

Goal: Practice nextLine(), numeric reads, and clean prompts.

Revision Checkpoint

  • Import: Scanner comes from java.util.
  • nextLine(): Reads a full line including spaces.
  • nextInt(): Reads one integer token.
  • Newline issue: Use an extra nextLine() after numeric reads before reading a full line.
  • Validation: Methods like hasNextInt() help avoid input mismatch errors.

Before the quiz: Explain why nextLine() may appear to skip after nextInt().

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

easyJava
Quiz: Scanner
10 questions5 min
Lesson 7 of 10 in 1. Java Fundamentals
Previous in 1. Java Fundamentals
6. Arrays & The Enhanced For Loop
Next in 1. Java Fundamentals
8. Mathematical Operations & The Math Class
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories