Java Reading Numeric Input

In the last lesson you learned about Java reading string input. The keyboard only sends text, so type 25 and Java first sees the characters 2 and 5, not the number. This lesson turns that text into real numbers, and handles the moment a user types hello where a number should go.

πŸ”’ Reading a whole number with nextInt()

Read a whole number (no decimal point, type int) with the Scanner method nextInt().

This program reads one number and prints it doubled, so you can see it really is a number now.

import java.util.Scanner;
public class ReadWhole {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a whole number: ");
int number = scanner.nextInt(); // βœ… reads an int
System.out.println("Double that is " + (number * 2));
}
}

Line by line:

  • Scanner connects to System.in, the keyboard.
  • print shows the prompt and keeps the cursor on the same line.
  • nextInt() reads the typed number into number as an int.
  • The math works because number holds a real number, not text.

Output

Enter a whole number: 21
Double that is 42

πŸ’΅ Reading a decimal with nextDouble()

For numbers with a decimal point (type double), use nextDouble().

  • A price can be 9.99. A temperature can be 36.6.
  • Reading 9.99 with nextInt() crashes, because it is not a whole number.

This program reads a price and shows it plus tax, so the decimal matters.

import java.util.Scanner;
public class ReadDecimal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the price: ");
double price = scanner.nextDouble(); // βœ… reads a double
double withTax = price * 1.10; // add 10% tax
System.out.println("Price with tax: " + withTax);
}
}

nextDouble() reads the decimal into price, then * 1.10 adds ten percent tax. A price like 49.50 cannot fit in an int, so double is the right home for any number with a fraction.

Output

Enter the price: 49.50
Price with tax: 54.450000000000003

That long tail of digits is normal for double. Computers store decimals in a way that is not always exact, so the value is correct even if it looks messy. The next lesson shows how to round and format it.

πŸ” Reading other number types

Scanner has a matching read method for each number type. This program reads a long for a very big number and a boolean for a true or false answer.

import java.util.Scanner;
public class MoreTypes {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a big number (population): ");
long population = scanner.nextLong(); // βœ… very large whole number
System.out.print("Are you subscribed? (true/false): ");
boolean subscribed = scanner.nextBoolean(); // βœ… true or false
System.out.println("Population: " + population);
System.out.println("Subscribed: " + subscribed);
}
}

What each one does:

  • nextLong() reads a long β€” like an int but for much bigger whole numbers, like a population or a phone number.
  • nextBoolean() reads a boolean; the user must type the word true or false.

Output

Enter a big number (population): 1428627663
Are you subscribed? (true/false): true
Population: 1428627663
Subscribed: true

Which method reads which type:

You wantJava typeScanner method
Whole numberintnextInt()
Decimal numberdoublenextDouble()
Very large whole numberlongnextLong()
True or falsebooleannextBoolean()

βž• Worked example: add two numbers

This program reads two numbers and prints their sum β€” the classic first interactive program.

import java.util.Scanner;
public class Adder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int first = scanner.nextInt();
System.out.print("Enter the second number: ");
int second = scanner.nextInt();
int sum = first + second;
System.out.println("The sum is " + sum);
}
}

Two nextInt() reads go into their own variables, so neither overwrites the other, then sum adds them and prints.

Output

Enter the first number: 8
Enter the second number: 5
The sum is 13

🧾 Worked example: a small bill calculator

This shop bill mixes number types. It reads the item count, the price of one item, and the age for a senior discount, then prints the total.

import java.util.Scanner;
public class Bill {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter quantity: ");
int quantity = scanner.nextInt();
System.out.print("Enter item price: ");
double price = scanner.nextDouble();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
double total = quantity * price;
if (age >= 60) {
total = total * 0.90; // seniors get 10% off
}
System.out.println("Items: " + quantity);
System.out.println("Price each: " + price);
System.out.println("Total to pay: " + total);
}
}

Line by line:

  • quantity is an int, because you buy whole items.
  • price is a double, because it can be 12.50.
  • age is an int, then checked.
  • total is quantity times price.
  • Age sixty or more takes ten percent off by multiplying by 0.90.
  • The bill prints all three values.

Output

Enter quantity: 3
Enter item price: 12.50
Enter your age: 65
Items: 3
Price each: 12.5
Total to pay: 33.75

πŸ’₯ When the user types text: InputMismatchException

Here is the problem that catches everyone: you call nextInt() and the user types hello. Java cannot turn hello into an int, so it stops the program with an error called InputMismatchException. An error that stops the program is called an exception.

This program reads a number with no guard at all.

import java.util.Scanner;
public class NoGuard {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt(); // ❌ crashes if the user types text
System.out.println("You entered " + number);
}
}

Type hello and the program does not print a wrong answer. It stops with a red error.

Output

Enter a number: hello
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at NoGuard.main(NoGuard.java:8)

The stack of lines shows where the crash happened. Only the first line matters: InputMismatchException means the input did not match the type the method wanted.

πŸ›‘οΈ Guarding with hasNextInt()

hasNextInt() lets you look before you leap.

  • It returns true if a whole number is waiting, false if not.
  • It only checks; it removes nothing from the input.
  • So you ask first, then call nextInt() only when it is safe.

This version checks before reading, so a wrong entry never crashes the program.

import java.util.Scanner;
public class SafeRead {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
if (scanner.hasNextInt()) { // βœ… look before you read
int number = scanner.nextInt();
System.out.println("You entered " + number);
} else {
System.out.println("That was not a whole number.");
}
}
}

Now hello makes hasNextInt() return false, so you print a calm message instead of crashing. There is a matching hasNextDouble() for decimals.

Output

Enter a number: hello
That was not a whole number.

πŸ”„ Keep asking until the input is valid

A single check is good, but often you want to keep asking until the user gives a real number. A while loop repeats while a condition stays true.

This program loops until a whole number arrives, clearing the bad text each time.

import java.util.Scanner;
public class KeepAsking {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
while (!scanner.hasNextInt()) { // not a whole number?
scanner.next(); // βœ… throw away the bad text
System.out.print("Please enter a whole number: ");
}
int age = scanner.nextInt();
System.out.println("Your age is " + age);
}
}

The key line is scanner.next():

  • Leave the bad word in place and the loop spins forever on it.
  • So we read and discard it, then ask again.
  • Once hasNextInt() sees a whole number, the loop ends and nextInt() reads it safely.

Output

Enter your age: hello
Please enter a whole number: thirty
Please enter a whole number: 30
Your age is 30

πŸͺ€ The nextInt-then-nextLine newline trap

One more thing to watch when you mix numbers and text:

  • nextInt() grabs the number but leaves the Enter key behind.
  • The next nextLine() reads that leftover, so the text comes out empty.
  • Fix it with one scanner.nextLine() to clear the leftover Enter first.

This snippet shows the trap and the fix.

// ❌ The name comes out empty β€” nextLine reads the leftover Enter
int age = scanner.nextInt();
String name = scanner.nextLine();
// βœ… Clear the leftover Enter first, then read the text
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();

This trap is so common it has a full walkthrough of its own. For the complete story and pictures of the input queue, see Java reading string input.

πŸ”€ Another way: parse strings to numbers

A second style avoids the newline trap entirely. Read the whole line with nextLine(), then convert the text yourself.

  • Integer.parseInt() turns text into a whole number.
  • Double.parseDouble() turns text into a decimal.

This program reads two lines, converts them to numbers, and adds them.

import java.util.Scanner;
public class ParseInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int first = Integer.parseInt(scanner.nextLine()); // βœ… text β†’ int
System.out.print("Enter the price: ");
double price = Double.parseDouble(scanner.nextLine()); // βœ… text β†’ double
System.out.println("Number: " + first);
System.out.println("Price: " + price);
}
}

Why it works:

  • Every read is a nextLine(), so each takes the whole line including its Enter key.
  • Nothing is left behind, so the newline trap cannot happen.
  • The cost: non-number text makes parseInt() throw a NumberFormatException, the parsing cousin of the mismatch error.

Output

Enter the first number: 8
Enter the price: 9.99
Number: 8
Price: 9.99

⚠️ Common Mistakes

A few slip-ups catch almost everyone.

No guard, so text crashes the program. Calling nextInt() straight away means one wrong keystroke ends everything with an InputMismatchException.

// ❌ Crashes the moment the user types text
int n = scanner.nextInt();
// βœ… Check first, read only when it is safe
if (scanner.hasNextInt()) {
int n = scanner.nextInt();
}

Looping without clearing the bad input. If you check with hasNextInt() in a loop but never remove the wrong word, the loop spins forever on the same text.

// ❌ Infinite loop β€” the bad word never leaves the queue
while (!scanner.hasNextInt()) {
System.out.print("Try again: ");
}
// βœ… Throw away the bad word, then loop
while (!scanner.hasNextInt()) {
scanner.next();
System.out.print("Try again: ");
}

The nextInt then nextLine trap. Reading a number and then a line of text leaves a skipped, empty line. Clear the leftover Enter first.

// ❌ The name comes out empty
int age = scanner.nextInt();
String name = scanner.nextLine();
// βœ… Clear the leftover Enter, then read the text
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();

βœ… Best Practices

Habits for clean numeric input.

  • Match the method to the value. Whole number β†’ nextInt(), decimal β†’ nextDouble(), very big whole number β†’ nextLong(), true or false β†’ nextBoolean().
  • Look before you read. Use hasNextInt() or hasNextDouble() so wrong input never crashes the program.
  • Loop until valid. When the input must be a number, keep asking, and clear the bad text with scanner.next() inside the loop.
  • Clear the newline. After nextInt() or nextDouble(), add a scanner.nextLine() before reading a line of text.
  • Prompt for the exact type. Tell the user β€œEnter a whole number” so they know what to type. Clear prompts prevent most mismatch errors.
  • Know the parse option. Reading lines and converting with Integer.parseInt() and Double.parseDouble() sidesteps the newline trap.

🧩 What You’ve Learned

Your programs can do real math on what the user types now.

  • βœ… Read numbers with the matching method: nextInt(), nextDouble(), nextLong(), nextBoolean().
  • βœ… Typing text where a number is expected throws an InputMismatchException.
  • βœ… Guard reads with hasNextInt() so a wrong entry never crashes the program.
  • βœ… Use a validation loop to keep asking, and clear bad input with scanner.next().
  • βœ… Mixing nextInt() with nextLine() causes the skipped line trap, so clear the leftover Enter.
  • βœ… You can read lines and convert with Integer.parseInt() and Double.parseDouble() instead.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    Which method reads a whole number like 42 from the user?

    Why: nextInt() reads the next value and gives back an int, so you can do math with it right away.

  2. 2

    What happens if you call nextInt() and the user types 'hello'?

    Why: nextInt() cannot turn 'hello' into a number, so Java stops the program with an InputMismatchException.

  3. 3

    How do you safely check before reading a whole number?

    Why: hasNextInt() returns true only when a whole number is waiting, so you read with nextInt() only when it is safe.

  4. 4

    Which method turns the text '25' into the number 25?

    Why: Integer.parseInt() takes a piece of text and returns an int, which is handy when you read input as full lines.

πŸš€ What’s Next?

You can read numbers cleanly and guard them against bad input. But a decimal can still print as a messy tail like 54.450000000000003. Next, learn to round and line up numbers so your output looks clean.

Java Formatting Output

Share & Connect