java · level 1 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A lets your program ask a question.
So far your programs only talk. To listen, they need a Scanner, a tool that reads : whatever the person types. Borrow it with on the very first line.
Then make one: Scanner keyboard = new Scanner(System.in);. new builds a fresh tool, and System.in means the keyboard. We keep it in a box called keyboard.
keyboard.nextLine() waits while the person types an answer and presses Enter. It gives back what they typed as a String, so store it in a box.
Ask with print, not println, so the answer is typed on the same line as the question.
guess first
Someone types crisps. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Favourite snack? ");
String snack = keyboard.nextLine();
System.out.println("Yum, " + snack);
}
}
your turn
Your turn. Write the second question.
Write a question asking for a favourite food between the quotes on line 7. End it with a space. We will answer Sam and pancakes.
output
press run to see what happens
fix it
The answer went missing. Can you fix it?
output
press run to see what happens
- Java cannot find
name. Where is a box called name made? - Line 6 reads the answer, but no box catches it, so it is thrown away.
- Put
String name =in front ofkeyboard.nextLine();on line 6, then press run.
nailed it
your program asked and listened. :D
import java.util.Scanner;borrows the tool that reads typing.keyboard.nextLine()waits, then gives back what was typed.- Store the answer in a
Stringbox to use it.
new words in your collection
- input
- import
- Scanner
This lesson isn’t saved. A free account remembers every lesson you finish.