Java Arena
Step 4 of 4

Several inputs in order

Each call to nextLine() reads the next line of input, so a program can read as many lines as it needs, one after another. They're read in order: the first nextLine() gets the first line, the second gets the second, and so on. The program waits at each nextLine() until a line is there.

Scanner scanner = new Scanner(System.in);
System.out.println("First word?");
String first = scanner.nextLine();
System.out.println("Second word?");
String second = scanner.nextLine();
System.out.println(second + " " + first);
Input
world
hello
Output
First word?
Second word?
hello world

The variables keep their values, so the program can print them in any order and as often as it likes. Only the reading has to follow the order of the input.

If a program asks for more lines than the input has, it stops with an error: NoSuchElementException: No line found. When that happens on this site, the result explains it. It usually means the program reads one line too many.

Your task

Challenge 1 of 3

Ask two questions and print the answers. For the input blue and whale the program prints:

Favorite color?
Favorite animal?
Color: blue
Animal: whale

Challenge 2

Read three lines and print them back in reverse order. For the input one, two and three the program prints:

three
two
one

Challenge 3

Write a tiny story generator. Ask for a hero's name and a place, then print a three-line story that uses each of them more than once. For the input Ada and Helsinki the program prints:

Hero's name?
A place?
Once upon a time, Ada set off for Helsinki.
Ada walked for days and days.
When Ada finally reached Helsinki, the whole town cheered.