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.
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
Java's Key Parsing Methods
Integer.parseInt() in Detail
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
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.
int n = Integer.parseInt(bad); // CRASH!
// Exception in thread "main"
// java.lang.NumberFormatException:
// For input string: "twelve"
Handling Errors with try-catch
try {
int num = Integer.parseInt(input);
System.out.println("Parsed: " + num);
} catch (NumberFormatException e) {
System.out.println("Invalid number!");
}
Step-by-Step Parsing Checklist
Example 1: Basic Integer Parsing
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
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
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().
int age = sc.nextInt(); // reads "17" but leaves \n
String name = sc.nextLine(); // reads leftover \n (empty!)
Common Mistakes
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
Consider this code:
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
String name = sc.nextLine();
System.out.println(x + " " + name);
The user enters 5 on the first line and Alice on the second line.
What does the program print?
Question 5 of 5
Which input would not cause a NumberFormatException with Double.parseDouble()?