AI Hints
Home›Java Tutorial›Reading Input with Scanner, Reading Numbers, Practice: A Receipt
Java · Lesson 26 of 120

Reading Numbers

NextInt and nextDouble.

⏱ 2 min read▶ Video at 33:51🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Scanner can read numbers too. Next int reads a whole number, and next double reads a decimal. They give you numbers you can do maths with.

  • nextInt()
  • nextDouble()
  • Ready for maths

Numbers from the keyboard

Next int reads a whole number. Next double reads a decimal. Then we use them in sums. Run it. The user typed twenty nine, and one point seven two. Next year, they'll be thirty. And their height in centimetres is one hundred and seventy two.

Main.javajava
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Your age: ");
        int age = in.nextInt();
        System.out.print("Your height in metres: ");
        double height = in.nextDouble();
        System.out.println("Next year you'll be " + (age + 1));
        System.out.println("In cm, that's " + height * 100);
    }
}
Input typed: 29 · 1.72
Output
Your age: 29
Your height in metres: 1.72
Next year you'll be 30
In cm, that's 172.0

The classic trap

Mixing next int and next line has a trap. Next int reads the number, but leaves the enter key behind. The next, next line would read that empty leftover, instead of the name. An extra next line throws the leftover away. Run it. Now the name is read correctly.

Main.javajava
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Age: ");
        int age = in.nextInt();
        in.nextLine();
        System.out.print("Name: ");
        String name = in.nextLine();
        System.out.println(name + " is " + age);
    }
}
Input typed: 41 · Jon
Output
Age: 41
Name: Jon
Jon is 41

Text to numbers

Sometimes you already have a number, stored as text. Integer dot parse int turns text into an int. Double dot parse double does the same, for decimals. And String dot value of goes the other way. Run it. Forty three, five point zero, and forty two with an exclamation mark.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String text = "42";
        int n = Integer.parseInt(text);
        System.out.println(n + 1);
        double d = Double.parseDouble("2.5");
        System.out.println(d * 2);
        String back = String.valueOf(n);
        System.out.println(back + "!");
    }
}
Output
43
5.0
42!

Summary

Next int and next double read numbers. After them, add a next line, before reading text. Parse int turns text into a number. Next, a practice receipt.

Key takeaways
  • nextInt(), nextDouble()
  • Watch the leftover enter
  • Integer.parseInt
Next up: Practice: A Receipt — put module three together