So far we have been printing things out. But what about getting input from the user?
That is where the Scanner class comes in. It lets you read whatever the
user types into the console.
Setting Up Scanner
To use Scanner, you first need to import it. Imports go at the top of your file,
before the class declaration. Then you create a Scanner object that reads from
System.in โ the standard input stream.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
The program asks for your name, you type it in, hit Enter, and Java says hello back. It is like having a conversation with your computer. Well, almost.
Reading Different Types
Scanner can handle more than just text. You can read numbers too. Here is a program that takes two numbers and adds them together:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int first = scanner.nextInt();
System.out.print("Enter second number: ");
int second = scanner.nextInt();
int sum = first + second;
System.out.println("Sum: " + sum);
}
}
Common Scanner Methods
Here is a quick reference of the methods you will use most:
nextLine()โ reads a whole line of text (including spaces)next()โ reads a single word (stops at spaces)nextInt()โ reads an integernextDouble()โ reads a decimal numbernextBoolean()โ reads true or false
A Note About nextLine() After nextInt()
Here is something that trips up almost every beginner. If you use nextInt()
and then nextLine(), the nextLine() will appear to be
skipped. This happens because nextInt() leaves a newline character in
the input buffer, and nextLine() reads that immediately.
The fix is simple โ add an extra nextLine() after nextInt()
to consume that leftover newline. We will cover this in detail later, but keep it
in the back of your mind.