Scanner Class in Java

The Scanner class in Java is part of the java.util package and is used to read input from various sources like the keyboard, files, or strings. It provides methods to parse primitive types (int, double, etc.) and strings using regular expressions. 1. Importing the Scanner Class To use the Scanner class, you need to import it: import java.util.Scanner; 2. Creating a Scanner Object You can create a Scanner object to read input from different sources: Read from System.in (Keyboard Input) Scanner scanner = new Scanner(System.in); Read from a File Scanner fileScanner = new Scanner(new File("input.txt")); Read from a String Scanner stringScanner = new Scanner("Hello World 123"); 3. Common Scanner Methods The Scanner class provides various methods to read different types of input: Method Description next() Reads a single String (token) until whitespace nextLine() Reads an entire line (including spaces) nextInt() Reads an integer nextDouble() Reads a double nextBoolean() Reads a boolean hasNext() Checks if there is another token hasNextInt() Checks if the next token is an integer close() Closes the scanner to prevent resource leaks 4. Reading Input from the User Example 1: Reading Different Data Types 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(); // Reads full line System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.print("Enter your height (in meters): "); double height = scanner.nextDouble(); System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Height: " + height + "m"); scanner.close(); // Always close the scanner } } Output: Enter your name: John Doe Enter your age: 25 Enter your height (in meters): 1.75 Name: John Doe Age: 25 Height: 1.75m Example 2: Reading Multiple Words Scanner scanner = new Scanner(System.in); System.out.print("Enter three words: "); String word1 = scanner.next(); // Reads first word String word2 = scanner.next(); // Reads second word String word3 = scanner.next(); // Reads third word System.out.println("Word 1: " + word1); System.out.println("Word 2: " + word2); System.out.println("Word 3: " + word3); scanner.close(); Output: Enter three words: Java Scanner Example Word 1: Java Word 2: Scanner Word 3: Example 5. Handling Input Errors If the user enters invalid input (e.g., a string when expecting an integer), InputMismatchException is thrown. To handle this, use hasNextInt(), hasNextDouble(), etc. Example: Safe Input Reading Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); if (scanner.hasNextInt()) { int num = scanner.nextInt(); System.out.println("You entered: " + num); } else { System.out.println("Invalid input! Please enter an integer."); } scanner.close(); 6. Important Notes Always close the scanner (scanner.close()) to avoid memory leaks. Mixing nextLine() with nextInt()/nextDouble() can cause issues because nextInt() does not consume the newline character. To fix this, call nextLine() after nextInt() to consume the leftover newline. int num = scanner.nextInt(); scanner.nextLine(); // Consumes the leftover newline String text = scanner.nextLine(); Use hasNext() methods to check input validity before reading. Conclusion The Scanner class is a powerful tool for reading user input in Java. It supports various data types and provides methods to safely read and validate input. Always remember to close the scanner to free resources. Would you like more examples or specific use cases?

May 5, 2025 - 16:06
 0
Scanner Class in Java

The Scanner class in Java is part of the java.util package and is used to read input from various sources like the keyboard, files, or strings. It provides methods to parse primitive types (int, double, etc.) and strings using regular expressions.

1. Importing the Scanner Class

To use the Scanner class, you need to import it:

import java.util.Scanner;

2. Creating a Scanner Object

You can create a Scanner object to read input from different sources:

Read from System.in (Keyboard Input)

Scanner scanner = new Scanner(System.in);

Read from a File

Scanner fileScanner = new Scanner(new File("input.txt"));

Read from a String

Scanner stringScanner = new Scanner("Hello World 123");

3. Common Scanner Methods

The Scanner class provides various methods to read different types of input:

Method Description
next() Reads a single String (token) until whitespace
nextLine() Reads an entire line (including spaces)
nextInt() Reads an integer
nextDouble() Reads a double
nextBoolean() Reads a boolean
hasNext() Checks if there is another token
hasNextInt() Checks if the next token is an integer
close() Closes the scanner to prevent resource leaks

4. Reading Input from the User

Example 1: Reading Different Data Types

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(); // Reads full line

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.print("Enter your height (in meters): ");
        double height = scanner.nextDouble();

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height + "m");

        scanner.close(); // Always close the scanner
    }
}

Output:

Enter your name: John Doe
Enter your age: 25
Enter your height (in meters): 1.75
Name: John Doe
Age: 25
Height: 1.75m

Example 2: Reading Multiple Words

Scanner scanner = new Scanner(System.in);
System.out.print("Enter three words: ");
String word1 = scanner.next(); // Reads first word
String word2 = scanner.next(); // Reads second word
String word3 = scanner.next(); // Reads third word

System.out.println("Word 1: " + word1);
System.out.println("Word 2: " + word2);
System.out.println("Word 3: " + word3);

scanner.close();

Output:

Enter three words: Java Scanner Example
Word 1: Java
Word 2: Scanner
Word 3: Example

5. Handling Input Errors

If the user enters invalid input (e.g., a string when expecting an integer), InputMismatchException is thrown. To handle this, use hasNextInt(), hasNextDouble(), etc.

Example: Safe Input Reading

Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");

if (scanner.hasNextInt()) {
    int num = scanner.nextInt();
    System.out.println("You entered: " + num);
} else {
    System.out.println("Invalid input! Please enter an integer.");
}

scanner.close();

6. Important Notes

  1. Always close the scanner (scanner.close()) to avoid memory leaks.
  2. Mixing nextLine() with nextInt()/nextDouble() can cause issues because nextInt() does not consume the newline character. To fix this, call nextLine() after nextInt() to consume the leftover newline.
   int num = scanner.nextInt();
   scanner.nextLine(); // Consumes the leftover newline
   String text = scanner.nextLine();
  1. Use hasNext() methods to check input validity before reading.

Conclusion

The Scanner class is a powerful tool for reading user input in Java. It supports various data types and provides methods to safely read and validate input. Always remember to close the scanner to free resources.

Would you like more examples or specific use cases?