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
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); }}
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 + "!"); }}