Java Arena
Step 4 of 6

Reading integers

scanner.nextLine() always gives text, a String, even when the user types digits. To calculate with the number, the text has to be turned into an int. Integer.valueOf(...) does that:

Scanner scanner = new Scanner(System.in);
System.out.println("How old are you?");
int age = Integer.valueOf(scanner.nextLine());
System.out.println("Next year you'll be " + (age + 1) + ".");
Input
29
Output
How old are you?
Next year you'll be 30.

Reading and converting fit on one line: the inner part, scanner.nextLine(), runs first and gives the text "29", and Integer.valueOf turns it into the number 29. (age + 1 in parentheses is calculated before it's joined to the text; the next module is all about calculating.)

Integer.parseInt(...) does the same job, and you'll see both in Java code. If the text isn't a whole number, for example twenty or 2.5, the program stops with a NumberFormatException.

Your task

Challenge 1 of 3

Fill in the blank, so the program turns the line it reads into an int.

Challenge 2

Ask for a lucky number, read it as an int, and print it in a sentence. For the input 7 the program prints:

What is your lucky number?
Your lucky number is 7.

Challenge 3

Read two whole numbers, one per line, and print them on one line. No calculating yet. For the input 4 and 9 the program prints:

First number:
Second number:
You gave 4 and 9.