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.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 9 figures

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

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.

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.

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.

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.

Input Parsing Flow in JavaKeyboardUser types "42"System.inraw byte streamScannerwraps streamnextLine() / next()returns String "42"Parse attemptInteger.parseInt()FAIL: "hello"OK: "42"NumberFormatExceptioncatch → re-prompt userint value = 42ready to use!
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.

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

Scannersc=newScanner(System.in);intnum=sc.nextInt();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

doubleprice=sc.nextDouble();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

Stringtext=sc.nextLine();intnum=Integer.parseInt(text);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

doubleval=Double.parseDouble(text);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.

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.

try-catch Pattern for Input ValidationTRY BLOCKString s = sc.nextLine();int n = Integer.parseInt(s);// Use n normally✓ Success PathProgram continues normallyInput: "42" → n = 4242 + 8 = 50 ✓CATCH BLOCKthrows!catch (NumberFormatException e) {System.out.println("Invalid number!");⟳ Re-prompt UserAsk for input againInput: "abc" → Exception!"Invalid number!" printed
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.

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

Common input format issues and their outcomes

💡

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.

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

    Step 1 — Set Up the Scanner and Variables

    Create 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. 2

    Step 2 — Create a while Loop

    Wrap 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. 3

    Step 3 — Read and Parse Inside a try Block

    Inside 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. 4

    Step 4 — Catch the Exception

    Add 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. 5

    Step 5 — Use the Validated Value

    After 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

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

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

Comparing two parsing approaches

✦

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.

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 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)

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

Explain why Java cannot directly use the String "100" in an arithmetic expression like "100" + 50. What would Java actually produce, and why?
Show answer
Java treats "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

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.
Show answer
The correct line is: 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

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);
Show answer
Wrap the parsing and output inside a try block, and add a catch for NumberFormatException: 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

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.
Show answer
Here is a complete solution: 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

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.
Show answer
This is the "dangling newline" problem. When the user types 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.

Varsity Tutors • Java • Parsing Numeric Input