Scanner
- Java course
- Beginner
- Lesson 94/116
- 4 min
Learn to read input with Scanner.
Scanner: console input
In Java, the Scanner class reads input from the console. First import java.util.Scanner, then connect it to System.in.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("Hello " + name);Scanner can read text and numbers line by line or as space-separated tokens. It is good practice to print a question message before reading, so the user knows what to enter. When you are done, call close() to release the resource.
Release the resource with close
Scanner wraps a resource; when you are done, close() releases it. This is not critical in small console programs, but it matters when reading files.
Scanner input = new Scanner(System.in);
String line = input.nextLine();
System.out.println(line);
input.close();For console input, close() also closes System.in; you cannot read again in the same program. So in console programs, closing is usually left to the end. When reading files, closing the resource right away prevents memory leaks.
Practice Greet the user
Create a Scanner, read the user's name and greet them as Hello, <name>. The user will type Ayşe.
Starter code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Create a Scanner, read the name and greet
}
}Sample solution
Scanner input = new Scanner(System.in);
System.out.print("Ad: ");
String name = input.nextLine();
System.out.println("Merhaba, " + name);Expected output
Ad: Merhaba, Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which import is needed to use Scanner?
- import java.io.Scanner;
- import java.lang.Scanner;
- import java.util.Scanner; Correct answer
- import java.net.Scanner;
Explanation: the Scanner class lives in the java.util package, so you import java.util.Scanner.
2 Match each Scanner method to its purpose
| Term | Meaning |
|---|---|
nextLine() |
Reads whole line |
nextInt() |
Reads integer |
close() |
Closes resource |
new Scanner(System.in) |
Binds to console |
3 Bind Scanner to the console
Scanner input = new Scanner(System.____);
String name = input.nextLine();
Scanner input = new Scanner(System.in);
String name = input.nextLine();
Explanation: System.in is the standard input stream (keyboard).