01 / 21
42 int double

Parsing
Numeric Input

Learn how to convert String input into usable numbers in Java: from Integer.parseInt() to Double.parseDouble(), and handle format errors gracefully.

Java

Why Do We Need to Parse Input?

When a user types something into a program, Java receives it as a String: a sequence of characters. Even if the user types "42", Java sees it as the characters '4' and '2', not the number \( 42 \). To do math with it, we must convert (parse) the String into a numeric type.

The String-to-Number Pipeline

User Types "3.14" Scanner nextLine() parseDouble() String → double 3.14 String String Conversion double

Java's Key Parsing Methods

Integer.parseInt(s)
Converts a String s to a primitive int. Throws NumberFormatException if the String is not a valid integer.
Double.parseDouble(s)
Converts a String s to a primitive double. Accepts decimals and scientific notation like "3.14" or "2.5e3".

Integer.parseInt() in Detail

// Signature
public static int parseInt(String s)

// Usage
String input = "256";
int num = Integer.parseInt(input);
System.out.println(num + 10); // 266

Double.parseDouble() in Detail

// Signature
public static double parseDouble(String s)

// Usage
String input = "9.81";
double gravity = Double.parseDouble(input);
System.out.println(gravity * 2); // 19.62

parseInt vs parseDouble

Integer.parseInt() Double.parseDouble()
Return type int double
Accepts decimals? No Yes
Accepts "42"? Yes → \( 42 \) Yes → \( 42.0 \)
Accepts "3.14"? Throws exception Yes → \( 3.14 \)
Accepts "hello"? Throws exception Throws exception

When Parsing Fails

If the String cannot be converted to a number, Java throws a NumberFormatException. This is a runtime error that crashes the program unless you handle it.

String bad = "twelve";
int n = Integer.parseInt(bad); // CRASH!

// Exception in thread "main"
// java.lang.NumberFormatException:
// For input string: "twelve"

Handling Errors with try-catch

String input = "abc";
try {
  int num = Integer.parseInt(input);
  System.out.println("Parsed: " + num);
} catch (NumberFormatException e) {
  System.out.println("Invalid number!");
}

Step-by-Step Parsing Checklist

1
Read the input as a String using Scanner's nextLine() method.
2
Choose the right method: parseInt() for whole numbers, parseDouble() for decimals.
3
Wrap in try-catch to guard against NumberFormatException.
4
Provide feedback in the catch block: tell the user what went wrong.
5
Use the result as an int or double in your calculations.

Example 1: Basic Integer Parsing

import java.util.Scanner;

public class AgeReader {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter your age: ");
    String line = sc.nextLine();
    int age = Integer.parseInt(line);
    System.out.println("Next year: " + (age + 1));
  }
}

Example 2: Safe Double Parsing

Scanner sc = new Scanner(System.in);
System.out.print("Enter price: $");
String line = sc.nextLine();

try {
  double price = Double.parseDouble(line);
  double tax = price * 0.08;
  System.out.println("Tax: $" + tax);
} catch (NumberFormatException e) {
  System.out.println("Please enter a valid number.");
}

Example 3: Loop Until Valid

Scanner sc = new Scanner(System.in);
int num = 0;
boolean valid = false;

while (!valid) {
  System.out.print("Enter an integer: ");
  try {
    num = Integer.parseInt(sc.nextLine());
    valid = true;
  } catch (NumberFormatException e) {
    System.out.println("Not valid. Try again.");
  }
}
System.out.println("You entered: " + num);

Scanner's Built-in Number Methods

Scanner also has nextInt() and nextDouble() which read and parse in one step. However, they leave a leftover newline in the buffer, which causes bugs when mixing with nextLine().

// Quick but risky
int age = sc.nextInt();   // reads "17" but leaves \n
String name = sc.nextLine(); // reads leftover \n (empty!)

Common Mistakes

✕ Parsing a Decimal with parseInt
Calling Integer.parseInt("3.14") throws an exception. Use parseDouble() for decimal values, then cast to int if needed.
✕ Forgetting try-catch
User input is unpredictable. Without error handling, one bad input crashes the entire program.
✕ Not Trimming Whitespace
parseInt(" 42 ") with leading/trailing spaces throws an exception. Call .trim() on the String first.

Summary of Parsing Techniques

Method Returns Accepts Decimals Newline Bug?
Integer.parseInt(s) int No No
Double.parseDouble(s) double Yes No
Scanner.nextInt() int No Yes
Scanner.nextDouble() double Yes Yes

Question 1 of 5

What does Integer.parseInt("3.5") do at runtime?

Question 2 of 5

Which of the following is the most direct way to parse the String "99" into a double?

Question 3 of 5

What is the purpose of a try-catch block when parsing user input?

Question 4 of 5

What does the program print?

Question 5 of 5

Which input would not cause a NumberFormatException with Double.parseDouble()?