SECTION 1
Why Parsing Matters: A Brief History
Every time you type a number into a program, something surprising is happening behind the scenes. The computer doesn't actually receive a number — it receives text characters. The digit "7" arrives as a character code, not as the mathematical value seven. Converting that text into a real number that your program can add, subtract, or compare is called parsing. This distinction between text and numbers has been a core challenge in computing since the earliest days of programming.
1960s • Early Input Handling
1972 • C Language & scanf
scanf() with format specifiers, but provided little protection against malformed input — crashes were common.1995 • Java's Exception Model
try-catch blocks.2004 • The Scanner Class Arrives
Scanner class, giving students and professionals a simpler way to read and parse typed input from the console.Today, the core question remains the same: how does a Java program reliably turn a sequence of keyboard characters — like "42" or "3.14" — into an int or a double? And what should it do when someone types "hello" instead? This lesson answers both questions.
SECTION 2
Core Principles of Numeric Parsing
Before diving into code, you need to understand a few foundational ideas that govern how Java handles the conversion from text to numbers. These principles apply whether you're reading from the keyboard, a file, or a network stream.
All Input Starts as Text
System.in stream delivers raw characters. Even if you type 99, Java initially sees two separate '9' characters, not the integer ninety-nine.Parsing = Text → Number
String and producing a numeric primitive like int or double. Java provides dedicated methods for each numeric type.Format Mismatch = Exception
NumberFormatException (or InputMismatchException with Scanner). Your program must be ready for this.Validation Before or After
hasNextInt(), or reactively by catching exceptions with try-catch. Both strategies are essential tools.KEY TAKEAWAY
Exception does in Java.SECTION 3
How Input Flows Through a Java Program
The following diagram shows the complete journey of user input — from keystrokes to a usable numeric value. Notice the critical decision point where Java checks whether the text can be validly converted. Understanding this flow is the foundation for writing robust input-handling code.
System.in and Scanner to a parsing decision point. Valid numeric text becomes an int; invalid text triggers a NumberFormatException.As the diagram shows, the parse attempt is the critical gate. Before that point, everything is just text. After a successful parse, you have a real number that Java can use in arithmetic. The two paths — success and failure — are the two scenarios every input-handling program must account for.
SECTION 4
How Parsing Works in Java
Java provides two main approaches to parse numeric input. You can use the Scanner class methods that parse directly, or you can read input as a String and then use wrapper class static methods to convert it. Both approaches are important to understand.
Approach 1: Scanner's Built-In Parse Methods
SCANNER INTEGER INPUT
nextInt() reads the next token from input and attempts to parse it as an int. If the token is not a valid integer, it throws InputMismatchException.
SCANNER DOUBLE INPUT
nextDouble() works the same way but expects a decimal number like 3.14. Passing an integer like "5" is fine — Java widens it automatically.
Approach 2: Read String, Then Parse
INTEGER.PARSEINT
Integer.parseInt(String s) is a static method of the Integer wrapper class. It converts a String to an int. If the String contains non-numeric characters, it throws NumberFormatException.
DOUBLE.PARSEDOUBLE
Double.parseDouble(String s) converts a String to a double. Valid inputs include "3.14", "-2.5", and even "7" (which becomes 7.0).
Common Pitfall: The Dangling Newline
nextInt() followed by nextLine(), the newline character left behind by nextInt() gets consumed by nextLine() immediately, returning an empty string. Fix this by adding an extra sc.nextLine() call right after nextInt() to clear the leftover newline.SECTION 5
Handling Format Errors with try-catch
Users make mistakes. They type letters when you expect digits, add spaces in the wrong places, or enter decimals when you need whole numbers. Java's exception handling mechanism gives you a structured way to deal with these problems without crashing. The try-catch block is the primary tool for this.
The table below summarizes the most common input format problems you'll encounter and what exception each one triggers.
| User Input | Expected Type | Result | Exception Thrown |
|---|---|---|---|
"42" | int | ✓ 42 | None |
"3.14" | int | ✗ Fails | NumberFormatException |
"hello" | int | ✗ Fails | NumberFormatException |
"" | int | ✗ Fails | NumberFormatException |
" 42 " | int | ✗ Fails | NumberFormatException |
"3.14" | double | ✓ 3.14 | None |
"9999999999" | int | ✗ Overflow | NumberFormatException |
Common input format issues and their outcomes
Tip: Trim Before Parsing
" 42 " (with spaces) causes a failure with Integer.parseInt(). You can fix this by calling text.trim() before parsing to remove leading and trailing whitespace.SECTION 6
Worked Example: A Robust Age Prompt
Let's build a complete program that asks the user for their age, validates the input, and keeps asking until a valid number is entered. This is a pattern you'll use constantly in real programs.
Building an Input Loop with try-catch
- 1
Step 1 — Set Up the Scanner and Variables
Create aScannerconnected toSystem.in. Declare anint agevariable and aboolean validflag initialized tofalse. The flag will control our loop.Scanner sc = new Scanner(System.in); int age = 0; boolean valid = false; - 2
Step 2 — Create a while Loop
Wrap the input logic in awhile (!valid)loop. The loop will repeat until we successfully parse a valid age. Inside, print a prompt so the user knows what to enter.while (!valid) { System.out.print("Enter your age: "); - 3
Step 3 — Read and Parse Inside a try Block
Inside the loop, use atryblock. Read the full line withsc.nextLine(), then parse it withInteger.parseInt(). If parsing succeeds, setvalid = trueto exit the loop.try { String input = sc.nextLine(); age = Integer.parseInt(input.trim()); valid = true; } - 4
Step 4 — Catch the Exception
Add acatch (NumberFormatException e)block that prints a friendly error message. Becausevalidremainsfalse, the loop will repeat automatically.catch (NumberFormatException e) { System.out.println("That's not a valid number. Try again."); } } - 5
Step 5 — Use the Validated Value
After the loop, you can safely useagebecause it has been successfully parsed. Print a confirmation message.System.out.println("Your age is: " + age);
Sample Run
Enter your age: abc
That's not a valid number. Try again.
Enter your age: 3.5
That's not a valid number. Try again.
Enter your age: 17
Your age is: 17SECTION 7
Scanner Methods vs. Wrapper Class Parsing
Now that you've seen both approaches, it's helpful to compare them side by side. Each has trade-offs, and knowing when to use which will make your code cleaner and more reliable.
| Feature | Scanner (nextInt, nextDouble) | Wrapper (parseInt, parseDouble) |
|---|---|---|
| How you read | One method reads and parses | Read as String first, then parse |
| Exception type | InputMismatchException | NumberFormatException |
| Newline handling | Leaves newline in buffer (tricky) | nextLine() consumes newline (clean) |
| Pre-validation | hasNextInt() / hasNextDouble() | Must use try-catch or regex |
| Flexibility | Quick for simple programs | Better for complex validation logic |
| Best for | Competitions, quick scripts | Production code, AP CS projects |
Comparing two parsing approaches
KEY TAKEAWAY
nextInt() like a drive-through — fast and convenient, but if your order is wrong, the whole line backs up. Using nextLine() plus Integer.parseInt() is more like sitting down at a restaurant — you get the order on paper first, check it, then send it to the kitchen. The second approach gives you more control over error handling.SECTION 8
Looking Ahead: Advanced Input Handling
The techniques in this lesson form the foundation, but real-world Java applications use more sophisticated approaches. As you advance, you'll encounter these related concepts that build on what you've learned here.
| What You Learned Today | What Comes Next |
|---|---|
| Parsing one value at a time | Parsing multiple values from a single line using split() |
| Catching NumberFormatException | Custom exception classes for domain-specific validation |
| Console input with Scanner | Reading from files with BufferedReader and FileReader |
| Basic int and double parsing | Parsing dates, currencies, and locale-specific formats with NumberFormat |
| Simple text validation | Pattern matching with regular expressions (regex) |
From introductory to advanced input handling
For now, focus on mastering the try-catch pattern and the difference between Scanner methods and wrapper class parsing. These skills transfer directly into every advanced topic listed above. In AP Computer Science A, you'll see input parsing appear in free-response questions, often combined with loops and conditionals.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
"100" in an arithmetic expression like "100" + 50. What would Java actually produce, and why?Show answer
"100" as a String, not a number. When you use the + operator with a String and an int, Java performs string concatenation, not addition. The result would be the String "10050". To get the mathematical result 150, you must first parse the String into an int using Integer.parseInt("100"), and then add 50 to the resulting integer value.Question 2: BASIC CALCULATION
sc, trims whitespace, and parses it as a double. Store the result in a variable called price.Show answer
double price = Double.parseDouble(sc.nextLine().trim());. This chains three operations: sc.nextLine() reads the full line as a String, .trim() removes leading and trailing spaces, and Double.parseDouble() converts the cleaned String into a double value.Question 3: INTERMEDIATE
"seven". Rewrite it using a try-catch block so that it prints "Invalid input" instead of crashing:
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = Integer.parseInt(sc.nextLine());
System.out.println("You entered: " + num);Show answer
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
try {
int num = Integer.parseInt(sc.nextLine());
System.out.println("You entered: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid input");
}
The try block attempts the parse. If it fails, the JVM skips the remaining try-block statements and jumps into the catch block, which prints the error message instead of allowing a crash.Question 4: APPLIED
Show answer
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double fahrenheit = 0;
boolean valid = false;
while (!valid) {
System.out.print("Enter temperature in °F: ");
try {
fahrenheit = Double.parseDouble(sc.nextLine().trim());
valid = true;
} catch (NumberFormatException e) {
System.out.println("Please enter a valid number.");
}
}
double celsius = (fahrenheit - 32) * 5.0 / 9;
System.out.printf("%.1f°F = %.1f°C%n", fahrenheit, celsius);
}
}
The while loop keeps the program running until a valid double is parsed. The trim() call handles accidental spaces. Note the use of 5.0 / 9 instead of 5 / 9 to avoid integer division.Question 5: CRITICAL THINKING
sc.nextInt() to read an age, then immediately calls sc.nextLine() to read the user's full name. When run, the program skips the name input entirely. Explain why this happens and propose two different solutions.Show answer
17 and presses Enter, the input buffer contains "17\n". The method nextInt() consumes only "17", leaving "\n" in the buffer. The subsequent nextLine() then reads that leftover newline and returns an empty string, never waiting for the user's name.
Solution 1: Add a throwaway sc.nextLine() call immediately after nextInt() to consume the leftover newline.
Solution 2: Avoid nextInt() entirely. Read all input with nextLine() and parse numbers using Integer.parseInt(). This approach eliminates the dangling newline problem entirely and gives you a consistent input pattern.SUMMARY
Lesson Summary
Summary
In this lesson, you learned that all keyboard input arrives as text (Strings) and must be converted to numeric types through a process called parsing. Java offers two main approaches: using Scanner methods like nextInt() and nextDouble() for quick reads, or using wrapper class methods like Integer.parseInt() and Double.parseDouble() for more control.
When input doesn't match the expected format, Java throws exceptions such as NumberFormatException or InputMismatchException. You handle these gracefully using try-catch blocks, often inside a while loop that re-prompts the user. Remember to watch out for the dangling newline problem when mixing nextInt() with nextLine(), and consider using trim() to clean up whitespace before parsing.