Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
281: The Scanner Class for Input Parsing
Up until now, our programs have been pretty static—we've hardcoded values or passed them in as arguments. But if we want to build something that actually interacts with a user, we need a way to read input on the fly. That's where the Scanner class comes in. It's the Swiss Army knife for parsing basic text and numbers from the console.
Setting up the input stream
I want to build a simple "Daily Calorie Tracker." The goal is to let the user enter a food item and its calorie count, then sum them up. To start, we need to import java.util.Scanner and initialize it. I'll pass System.in into the constructor, which tells Java we want to listen to the standard input stream (your keyboard).
import java.util.Scanner;
public class CalorieTracker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalCalories = 0;
System.out.println("Welcome to the Calorie Tracker!");
// Logic goes here...
}
}
Capturing food and numbers
Now, I'll set up a loop to collect items. I need a String for the food name and an int for the calories. I'll use nextLine() for the text because food names often have spaces (like "Grilled Cheese"), and nextInt() for the numerical value. It seems straightforward enough.
while (true) {
System.out.print("Enter food name (or 'done' to finish): ");
String food = scanner.nextLine();
if (food.equalsIgnoreCase("done")) break;
System.out.print("Enter calories for " + food + ": ");
int calories = scanner.nextInt();
totalCalories += calories;
System.out.println("Current total: " + totalCalories);
}
The "disappearing input" bug
I just ran this, and it's behaving weirdly. The first item works perfectly. But the second time the loop runs, it completely skips the "Enter food name" prompt and immediately jumps to the calorie prompt, often crashing with an InputMismatchException.
I've run into this a hundred times in my career, and it's the most common "gotcha" with the Scanner class. Here is what's happening: nextInt() reads the number, but it doesn't consume the newline character (the Enter key) you pressed after typing the number. That newline character is still sitting in the buffer. When the loop restarts and hits nextLine(), it sees that leftover newline and thinks, "Oh, the user already pressed Enter!" and returns an empty string immediately.
Clearing the buffer for a clean loop
To fix this, we have to "flush" that leftover newline character. The simplest way is to call scanner.nextLine() immediately after scanner.nextInt(). This call doesn't save the result anywhere; it just clears the pipe so the next actual input prompt starts fresh.
while (true) {
System.out.print("Enter food name (or 'done' to finish): ");
String food = scanner.nextLine();
if (food.equalsIgnoreCase("done")) break;
System.out.print("Enter calories for " + food + ": ");
int calories = scanner.nextInt();
// The Fix: Consume the leftover newline character
scanner.nextLine();
totalCalories += calories;
System.out.println("Current total: " + totalCalories);
}
System.out.println("Your final daily total is: " + totalCalories);
One last pro tip: always remember to close your scanner with scanner.close() at the very end of your main method. While it's not always fatal in a small project, leaving system resources open is a bad habit that will haunt you when you start working with files or network sockets.
📋 Practical Task
Build a Retro RPG Character Sheet Generator
Create a program that allows a user to build a character for a role-playing game. Your program must use a Scanner to collect the following information in this specific order:
- Character Name: A String (can include spaces).
- Age: An integer.
- Class: A String (e.g., "Warrior", "Mage").
- Strength Score: An integer.
Requirement: Ensure that your program does not skip the "Class" input prompt after the "Age" input. After collecting all four pieces of data, print a formatted character sheet summary to the console.
There are no comments for now.