Reading Input
Most of the programs you’ve written so far have been self-contained. They compute something and print it, but everything is hardcoded. If you want to change the value, you edit the source code and rerun. That’s fine for practicing syntax, but it’s not how useful programs work.
To make a program actually respond to the person running it, you need to read input.
Now, you’re probably used to input meaning tapping a button, filling out a form, or swiping something on a screen. That’s how finished apps work, and eventually you’ll build things like that too. For now, you’re going to read input from the console; the same text window where you’ve been seeing output. It’s not glamorous, but it lets you make interactive programs immediately, without needing to build a UI first. Think of it as a scratchpad.
The Scanner class
Java has a built-in tool for reading console input called Scanner. To use it, you need two things you haven’t seen before: an import statement and the new keyword.
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); }}import java.util.Scanner tells Java you want to borrow the Scanner tool from its standard library. Without this line, Java doesn’t know what Scanner means.
new Scanner(System.in) creates a Scanner and connects it to System.in, the standard input stream, which is the keyboard by default. You store it in a variable called scanner so you can use it throughout your program.
You only need one Scanner for the whole program. Don’t create a new one every time you want to read something.
Scannercan do more than what’s covered here. You’ll come back to it in Chapter 7 with a fuller picture.
Reading Values
When someone types something and presses Enter, the computer receives it as raw text. But your program doesn’t want raw text, it wants an int, or a double, or a String. Scanner needs to know which type you’re expecting so it can do that conversion for you.
So instead of one general “read something” command, Scanner gives you a specific command for each type:
scanner.nextInt()reads the input and gives you anintscanner.nextDouble()reads the input and gives you adoublescanner.nextBoolean()reads the input and gives you abooleanscanner.next()reads a single word and gives you aString
The pattern is consistent: the name tells you what type comes back. If you want a double, you use nextDouble(). You don’t have to memorize these individually, just recognize the pattern.
Here’s a program that asks for your birth year and prints your approximate age:
When execution reaches scanner.nextInt(), the program pauses and waits. It does nothing until the user types a number and presses Enter. Then it resumes, storing whatever was typed into birthYear.
Notice System.out.print instead of System.out.println on the prompt line. That keeps the cursor on the same line as the prompt, so the user types right after it. It’s a small thing but it makes the program feel less clunky.
Always print a prompt before reading input. A program that just freezes silently is confusing, the user has no idea it’s waiting for them.
A more complete example
Let’s build something slightly more useful: a program that calculates your BMI from height and weight.
You can call Scanner methods as many times as you need, one read per value. Each call waits for the user to type something and press Enter.
What next() does (and doesn’t do)
scanner.next() reads one word. Specifically, one whitespace-delimited token. So if the user types John, you get "John". But if they type John Smith, you only get "John". The Smith gets left behind, waiting for the next read.
This works fine as long as you’re reading a single word. If you need to read a full line with spaces, there’s a different method for that: nextLine(). You’ll cover it properly in Chapter 7, along with some quirks that make it trickier than it looks.
The type has to match
One thing to be aware of: if you call nextInt() but the user types "hello", your program will crash with an error. The Scanner is trusting you to know what the user will type. For now, assume cooperative users. You’ll learn how to handle bad input gracefully later in the course.
Checkpoint
Why does Scanner have separate commands like nextInt() and nextDouble() instead of one general “read something” command?
What happens when your program reaches scanner.nextInt()?
A user runs your program and types John Smith when asked for their name. Your code reads it with scanner.next(). What does the variable contain?