Skip to content

Java Scanner class

What exactly is the Scanner class, you ask? Well, think of it as a magical wand that allows your Java programs to interact with users by reading input from the keyboard or other input sources. With the Scanner class, you can capture numbers, strings, and other types of data typed by the user, opening up a world of possibilities for dynamic and interactive programs.

Now, imagine you're creating a program that asks users for their name, age, and favorite color. How do you capture this information and make your program respond accordingly? Enter the Scanner class! Let me show you a simple example:

java
import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        // Create a Scanner object to read user input
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter their name
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        // Prompt the user to enter their age
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        // Prompt the user to enter their favorite color
        System.out.print("Enter your favorite color: ");
        String favoriteColor = scanner.next();

        // Display a personalized message using the captured information
        System.out.println("Hello, " + name + "! You are " + age + " years old and your favorite color is " + favoriteColor + ".");
    }
}

Isn't that wonderful? With just a few lines of code, we've created a program that interacts with the user, captures their input, and responds with a personalized message. All thanks to the Scanner class!

But wait, there's more! The Scanner class isn't just limited to reading input from the keyboard. It can also be used to read input from files, strings, and other input sources, making it incredibly versatile and powerful.

Absolutely! The Scanner class in Java is indeed versatile and can be used to read input not only from the keyboard but also from various other sources such as files, strings, and other input streams. Let me show you how:

Reading Input from Files

You can use the Scanner class to read input from files by passing a File object as the input source. Here's an example:

java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFromFileExample {
    public static void main(String[] args) {
        try {
            // Create a File object representing the input file
            File inputFile = new File("input.txt");
            
            // Create a Scanner object to read input from the file
            Scanner scanner = new Scanner(inputFile);

            // Read input from the file line by line
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            // Close the scanner
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

In this example, we're reading input from a file named "input.txt" and printing each line to the console.

Reading Input from Strings

You can also use the Scanner class to read input from strings using the Scanner(String source) constructor. Here's how:

java
import java.util.Scanner;

public class ReadFromStringExample {
    public static void main(String[] args) {
        String inputString = "Hello World! This is a test string.";
        
        // Create a Scanner object to read input from the string
        Scanner scanner = new Scanner(inputString);

        // Read input from the string word by word
        while (scanner.hasNext()) {
            String word = scanner.next();
            System.out.println(word);
        }

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

In this example, we're reading input from the string "Hello World! This is a test string." and printing each word to the console.

Reading Input from Other Input Sources

Besides files and strings, you can use the Scanner class to read input from various other input sources such as network sockets, input streams, and more. You can create a Scanner object using constructors that accept InputStream, Readable, or other input sources as parameters.

java
import java.io.InputStream;
import java.util.Scanner;

public class ReadFromInputStreamExample {
    public static void main(String[] args) {
        // Assume inputStream is an InputStream object representing some input source
        InputStream inputStream = System.in;
        
        // Create a Scanner object to read input from the input stream
        Scanner scanner = new Scanner(inputStream);

        // Read input from the input stream line by line
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            System.out.println(line);
        }

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

In this example, we're reading input from the standard input stream (System.in) and printing each line to the console.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.