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.

Feb 22, 202636 views0 likes0 fires
18px

[!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(); 

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
2 questions5 min

Continue Learning

8. Mathematical Operations & The Math Class

Beginner
7 min

9. Operators in Depth

Beginner
10 min

10. Block Scope & Variable Lifecycles

Beginner
8 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 Java Programming: From Zero to EnterpriseAll Categories