Creating a Scanner Object: The Basic Steps
To create a Scanner in Java, you write a single line that declares a new Scanner object and connects it to an input source. The most common source is System.in, which reads text the user types into the console. The line looks like this:
Scanner scanner = new Scanner(System.in);
Before you can use this line, you must import the Scanner class at the very top of your file, above your class declaration. Add this import statement:
import java.util.Scanner;
Once you have imported Scanner and created the object, you can read user input using methods like nextLine() to read an entire line of text, nextInt() to read a whole number, or nextDouble() to read a decimal number. When you are finished using the Scanner, close it with scanner.close() to free up system resources.
Key Takeaways
- Import the Scanner class with import java.util.Scanner; at the top of your Java file, before the class declaration.
- Create a Scanner object connected to user input by writing Scanner scanner = new Scanner(System.in);
- Use nextLine() to read a full line of text, nextInt() for whole numbers, and nextDouble() for decimal numbers.
- Always call scanner.close() when you finish reading input to prevent resource leaks.
- Scanner can read from files, strings, or the console depending on what you pass to its constructor.
Where Scanner Reads From
When you write new Scanner(System.in), you are telling Scanner to read from the keyboard—whatever the user types. But Scanner is flexible and can read from other sources too. If you want to read from a file instead, you pass a File object: Scanner scanner = new Scanner(new File("myfile.txt")); This requires an additional import: import java.io.File;
You can also create a Scanner that reads from a string already in memory. This is useful for testing or parsing data you already have: Scanner scanner = new Scanner("apple banana cherry"); The Scanner will treat the string as input and let you read words or lines from it using the same methods you would use for keyboard input.
Reading Different Types of Data
Once your Scanner is created, the method you call determines what kind of data you get back. nextLine() reads everything up to the next line break and returns it as a string—use this when you want a full sentence or line. nextInt() reads the next whole number and skips any whitespace before it. nextDouble() reads the next decimal number. next() reads the next single word (stops at whitespace).
A common mistake is mixing these methods. If you call nextInt() and then nextLine(), the nextLine() will read only the leftover line break from the previous input, giving you an empty string. To avoid this, read the line break separately or use nextLine() for everything and parse the numbers yourself.
A Complete Working Example
Here is a short program that creates a Scanner, reads a name and an age, and prints them back:
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.println("Hello " + name + ", you are " + age + " years old."); scanner.close(); } }
When you run this program, it prints "Enter your name: " and waits for you to type something. After you type a name and press Enter, it prints "Enter your age: " and waits for a number. Once you type a number and press Enter, it prints a greeting and closes the Scanner.
Checking If More Input Exists
Before you call a method like nextInt(), you can check whether the next piece of input actually exists and is the right type. Use hasNextLine() to check if there is another line, hasNextInt() to check if the next token is a whole number, and hasNextDouble() to check if it is a decimal. These methods return true or false.
This is especially useful when reading from a file or when you are not sure how much input is coming. A common pattern is a while loop that keeps reading as long as input exists:
while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); }
This loop reads and prints every line from the input source until there are no more lines. If you try to read without checking first and no input is available, your program will crash with an exception.
Common Mistakes to Avoid
Forgetting to import Scanner is the most common error. If you write new Scanner(System.in) without the import statement, the compiler will not recognize the Scanner class and your code will not compile. Always add import java.util.Scanner; at the top of your file.
Another frequent mistake is not closing the Scanner. While a Scanner that reads from System.in will not cause serious problems if left open, it is still good practice to close it. More importantly, if you create a Scanner that reads from a file, leaving it open can prevent other programs from accessing that file. Always call scanner.close() when you are done.
Mixing nextInt() and nextLine() causes confusing bugs. After you call nextInt(), the line break is still in the input buffer. The next call to nextLine() will read that leftover line break and return an empty string. To fix this, call scanner.nextLine() after nextInt() to consume the line break, or use nextLine() for everything and parse numbers manually.
Frequently Asked Questions
Do I need to import Scanner or does it come with Java automatically?
Scanner does not come automatically. You must write import java.util.Scanner; at the top of your file. It is part of the Java standard library, so you do not need to read anything, but the import statement is required for your code to compile.
Can I create more than one Scanner in the same program?
Yes, you can create multiple Scanner objects. Each one can read from a different source—one from the keyboard, one from a file, one from a string. Just give each Scanner a different variable name, like Scanner keyboard = new Scanner(System.in); and Scanner file = new Scanner(new File("data.txt"));
What happens if the user types a word when I call nextInt()?
Your program will crash with an InputMismatchException because the Scanner expected a number but found text instead. To prevent this, use hasNextInt() to check before calling nextInt(), or wrap the read in a try-catch block to handle the error gracefully.
Is System.in the only way to read keyboard input?
System.in is the standard way. Scanner is the easiest tool to use with it. There are other methods like BufferedReader, but Scanner is simpler for most programs and is what most Java beginners learn first.
Do I have to close the Scanner?
For System.in, closing is not strictly required, but it is good practice. For file-based Scanners, closing is important because it releases the file lock and lets other programs use the file. The safest approach is to always close your Scanner when you are done with it.