Java Scanner

Java Scanner is a class in the Java.util package that provides methods for reading input from various sources like standard input, files, and strings. It is widely used to read user input from the console, files, and other input sources.

The Scanner class is designed to break down input into tokens based on specific delimiters (such as whitespace or commas) and provides methods for retrieving those tokens as different types of data (such as integers, floats, or strings).

Here’s an example of using Scanner to read input from the console:

import java.util.Scanner;

public class MyClass {
  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.");
  }
}

In this example, we create a new Scanner object that reads input from the standard input stream (i.e., the console). We then prompt the user to enter their name and age and use the Scanner’s nextLine() and nextInt() methods to retrieve the input as a String and an int, respectively. Finally, we use these values to print a greeting to the user.

Java Scanner Class Declaration:

The Scanner class is part of the java.util package, so you need to import it at the beginning of your Java file using the following statement:

import java.util.Scanner;

Once you have imported the class, you can create a new instance of the Scanner class using the following syntax:Once you have imported the class, you can create a new instance of the Scanner class using the following syntax:

Scanner scanner = new Scanner(System.in);

In this example, we create a new Scanner object called scanner that reads input from the standard input stream (i.e., the console). You can also create a Scanner object that reads input from a file by passing a File object to the Scanner constructor, like this:

File file = new File("input.txt");
Scanner scanner = new Scanner(file);

This will create a new Scanner object that reads input from the specified file (input.txt in this example).

How to get Java Scanner:

The Scanner class is part of the Java standard library, so it is already included in any Java development environment you might be using. You don’t need to download or install any additional software to use it.

To use the Scanner class in your Java program, you need to import it using the import statement at the beginning of your file:

import java.util.Scanner;

After importing the Scanner class, you can create a new instance of it in your code like this:

Scanner scanner = new Scanner(System.in);

This creates a new Scanner object called scanner that reads input from the standard input stream (i.e., the console). You can then use the various methods provided by the Scanner class to read input from the user or from files, depending on your needs.

Java Scanner Class Constructors:

The Scanner class provides several constructors to create a new instance of the class, depending on the source of input you want to read. Here are the available constructors:

  1. Scanner(File source) – creates a new Scanner object that reads input from a file.
  2. Scanner(File source, String charsetName) – creates a new Scanner object that reads input from a file using the specified character set.
  3. Scanner(InputStream source) – creates a new Scanner object that reads input from an InputStream object, such as System.in.
  4. Scanner(InputStream source, String charsetName) – creates a new Scanner object that reads input from an InputStream object using the specified character set.
  5. Scanner(String source) – creates a new Scanner object that reads input from a String.
  6. Scanner(Readable source) – creates a new Scanner object that reads input from any object that implements the Readable interface, such as a BufferedReader or CharBuffer.
  7. Scanner(ReadableByteChannel source) – creates a new Scanner object that reads input from a ReadableByteChannel object.

Here’s an example of using the Scanner(File source) constructor to read input from a file:

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

public class MyClass {
    public static void main(String[] args) {
        try {
            File inputFile = new File("input.txt");
            Scanner scanner = new Scanner(inputFile);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        }
    }
}

In this example, we create a new File object representing a file called input.txt. We then create a new Scanner object that reads input from this file, and use a loop to read each line of the file until there is no more input. Finally, we close the Scanner object to release any resources it was using.

Java Scanner Class Methods:

The Scanner class provides various methods to read input from different sources and parse it into different data types. Here are some of the most commonly used methods:

  1. next() – reads the next token of input as a String, delimited by whitespace.
  2. nextInt() – reads the next token of input as an int.
  3. nextLine() – reads the next line of input as a String.
  4. nextDouble() – reads the next token of input as a double.
  5. useDelimiter(String pattern) – sets the delimiter for the Scanner object to the specified regular expression pattern.
  6. hasNext() – returns true if there is another token in the input, false otherwise.
  7. hasNextLine() – returns true if there is another line of input, false otherwise.
  8. close() – closes the Scanner object and releases any resources it was using.

Here’s an example of using some of these methods to read input from the console and parse it into different data types:

import java.util.Scanner;

public class MyClass {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.next();

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

        System.out.print("Enter your GPA: ");
        double gpa = scanner.nextDouble();

        System.out.println("Hello, " + name + "! You are " + age + " years old and have a GPA of " + gpa + ".");

        scanner.close();
    }
}

In this example, we create a new Scanner object that reads input from the console. We then use the next() method to read the next token of input (the user’s name), the nextInt() method to read the next token of input as an integer (the user’s age), and the nextDouble() method to read the next token of input as a double (the user’s GPA). Finally, we print out a message that includes the input values.

Example:

Here’s another example of using the Scanner class in Java to read input from a file and parse it into different data types:

Suppose you have a file called data.txt with the following contents:

John
Doe
25
3.8

You can use the following code to read this file and extract the values as strings and numbers:

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

public class MyClass {
    public static void main(String[] args) {
        try {
            File inputFile = new File("data.txt");
            Scanner scanner = new Scanner(inputFile);

            String firstName = scanner.next();
            String lastName = scanner.next();
            int age = scanner.nextInt();
            double gpa = scanner.nextDouble();

            System.out.println("Name: " + firstName + " " + lastName);
            System.out.println("Age: " + age);
            System.out.println("GPA: " + gpa);

            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
        }
    }
}

In this example, we create a new File object representing the data.txt file, and use a Scanner object to read its contents. We use the next() method twice to read the first and last name, the nextInt() method to read the age, and the nextDouble() method to read the GPA. Finally, we print out the values using the println() method. Note that we use a try-catch block to handle the FileNotFoundException that could be thrown if the file does not exist.