Scanner
The Scanner class in Java is used to get user input from various sources including the console (keyboard), files, and strings.
Basic Usage
Section titled “Basic Usage”To use the Scanner class, you first need to import it:
import java.util.Scanner;Then create a Scanner object:
// Create a Scanner object for console inputScanner scanner = new Scanner(System.in);Reading Different Types of Input
Section titled “Reading Different Types of Input”Reading Strings
Section titled “Reading Strings”System.out.print("Enter your name: ");String name = scanner.nextLine(); // Reads a line of textReading Integers
Section titled “Reading Integers”System.out.print("Enter your age: ");int age = scanner.nextInt(); // Reads an integerReading Floating Point Numbers
Section titled “Reading Floating Point Numbers”System.out.print("Enter your height in meters: ");double height = scanner.nextDouble(); // Reads a doubleReading a Single Word
Section titled “Reading a Single Word”System.out.print("Enter a word: ");String word = scanner.next(); // Reads until whitespaceImportant Methods
Section titled “Important Methods”| Method | Description |
|---|---|
nextLine() | Reads a line of text (until newline) |
next() | Reads the next token (word) |
nextInt() | Reads the next token as an int |
nextDouble() | Reads the next token as a double |
nextBoolean() | Reads the next token as a boolean |
hasNext() | Returns true if more tokens exist |
hasNextLine() | Returns true if more lines exist |
Common Issues
Section titled “Common Issues”Mixing nextLine() with other next methods
Section titled “Mixing nextLine() with other next methods”When you use nextInt() or other non-line methods followed by nextLine(), you may encounter issues because nextInt() doesn’t consume the newline character:
// Issue exampleint number = scanner.nextInt(); // User enters "42" and presses EnterString text = scanner.nextLine(); // This immediately returns empty string!Solution:
// Solutionint number = scanner.nextInt(); // User enters "42" and presses Enterscanner.nextLine(); // Consume the leftover newlineString text = scanner.nextLine(); // Now this waits for user inputClosing the Scanner
Section titled “Closing the Scanner”It’s good practice to close the Scanner when you’re done with it:
scanner.close();Reading from Files
Section titled “Reading from Files”You can also use Scanner to read from files:
import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;
public class ReadFile { public static void main(String[] args) { try { File file = new File("example.txt"); Scanner fileScanner = new Scanner(file);
while (fileScanner.hasNextLine()) { String line = fileScanner.nextLine(); System.out.println(line); }
fileScanner.close(); } catch (FileNotFoundException e) { System.out.println("File not found"); e.printStackTrace(); } }}