JAVA • INPUT AND OUTPUT

Parsing Numeric Input — Parse numeric input and handle input format issues (intro)

Learn how Java converts text from the keyboard into usable numbers, and what happens when the format is wrong.

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
Languages like FORTRAN and COBOL introduced formatted input statements, requiring programmers to declare exact column positions for numeric data on punch cards.
1972
C Language & scanf
The C programming language introduced scanf() with format specifiers, but provided little protection against malformed input — crashes were common.
1995
Java's Exception Model
Java launched with a robust exception-handling system, letting developers catch and respond to bad input gracefully using try-catch blocks.
2004
The Scanner Class Arrives
Java 5 introduced the 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.

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.

1

All Input Starts as Text

When a user types at the keyboard, Java's System.in stream delivers raw characters. Even if you type 99, Java initially sees two separate '9' characters, not the integer ninety-nine.
2

Parsing = Text → Number

Parsing is the act of interpreting a String and producing a numeric primitive like int or double. Java provides dedicated methods for each numeric type.
3

Format Mismatch = Exception

If the text cannot be interpreted as the requested type, Java throws a NumberFormatException (or InputMismatchException with Scanner). Your program must be ready for this.
4

Validation Before or After

You can validate input proactively using methods like hasNextInt(), or reactively by catching exceptions with try-catch. Both strategies are essential tools.
✦ KEY TAKEAWAY
Think of parsing like a language translator at an airport. A passenger hands over a form written in text. The translator must figure out which parts are numbers (flight number, passport number) and convert them into a format the computer system understands. If the handwriting is illegible or the passenger wrote words where numbers belong, the translator flags the problem — that's exactly what an Exception does in Java.

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.

The diagram traces user input from the keyboard through 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.

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
Scanner sc = new Scanner(System.in); int num = sc.nextInt();
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
double price = sc.nextDouble();
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
String text = sc.nextLine(); int num = Integer.parseInt(text);
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 val = Double.parseDouble(text);
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
When you call 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.

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 left panel shows the try block where parsing is attempted. If it succeeds (green), the program proceeds. If parsing fails (red arrow), control jumps to the catch block on the right, where you display an error message and optionally re-prompt.

The table below summarizes the most common input format problems you'll encounter and what exception each one triggers.

Common input format issues and their outcomes
User InputExpected TypeResultException Thrown
"42"int✓ 42None
"3.14"int✗ FailsNumberFormatException
"hello"int✗ FailsNumberFormatException
""int✗ FailsNumberFormatException
" 42 "int✗ FailsNumberFormatException
"3.14"double✓ 3.14None
"9999999999"int✗ OverflowNumberFormatException
💡 Tip: Trim Before Parsing
Notice that " 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.

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 VariablesCreate a Scanner connected to System.in. Declare an int age variable and a boolean valid flag initialized to false. The flag will control our loop.
Scanner sc = new Scanner(System.in); int age = 0; boolean valid = false;
2
Step 2 — Create a while LoopWrap the input logic in a while (!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 BlockInside the loop, use a try block. Read the full line with sc.nextLine(), then parse it with Integer.parseInt(). If parsing succeeds, set valid = true to exit the loop.
try { String input = sc.nextLine(); age = Integer.parseInt(input.trim()); valid = true; }
4
Step 4 — Catch the ExceptionAdd a catch (NumberFormatException e) block that prints a friendly error message. Because valid remains false, 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 ValueAfter the loop, you can safely use age because 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: 17

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.

Comparing two parsing approaches
FeatureScanner (nextInt, nextDouble)Wrapper (parseInt, parseDouble)
How you readOne method reads and parsesRead as String first, then parse
Exception typeInputMismatchExceptionNumberFormatException
Newline handlingLeaves newline in buffer (tricky)nextLine() consumes newline (clean)
Pre-validationhasNextInt() / hasNextDouble()Must use try-catch or regex
FlexibilityQuick for simple programsBetter for complex validation logic
Best forCompetitions, quick scriptsProduction code, AP CS projects
✦ KEY TAKEAWAY
Think of 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.

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.

From introductory to advanced input handling
What You Learned TodayWhat Comes Next
Parsing one value at a timeParsing multiple values from a single line using split()
Catching NumberFormatExceptionCustom exception classes for domain-specific validation
Console input with ScannerReading from files with BufferedReader and FileReader
Basic int and double parsingParsing dates, currencies, and locale-specific formats with NumberFormat
Simple text validationPattern matching with regular expressions (regex)

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain why Java cannot directly use the String "100" in an arithmetic expression like "100" + 50. What would Java actually produce, and why?
PROBLEM 2 — BASIC CALCULATION
Write a single line of Java code that reads a line of text from a Scanner object called sc, trims whitespace, and parses it as a double. Store the result in a variable called price.
PROBLEM 3 — INTERMEDIATE
A student writes the following code, but it crashes when the user enters "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);
PROBLEM 4 — APPLIED
You're building a temperature converter. The user enters a Fahrenheit value as text, and your program should convert it to Celsius using the formula C = (F − 32) × 5 / 9. Write a complete program that handles invalid input by re-prompting the user until they enter a valid decimal number. Use a while loop and try-catch.
PROBLEM 5 — CRITICAL THINKING
Consider this scenario: a program uses 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.

Lesson 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.

Varsity Tutors • Java • Parsing Numeric Input