Created: 2023-08-26 10:12
Status: #concept
Subject: Programming
Tags: Java java.util Java Class stdin

java.util.Scanner

A java.util Class that allows us to read user input as tokens to be parsed into primitive Java Data Types.

  • by default, the delimiter to separate the tokens is any whitespace Character unless we specify a .useDelimiter(String del).
  • we can use various next___() instance Methods to parse the "next" token.
  • typically, we use System.in as the target to scan within the Scanner() constructor, but we can also pass any Java Readable interface like Java Files.

import java.util.Scanner;

public class Program {

    public static void main(String[] args) {
        // we have to instantiate a Scanner object with System.in as an argument to the constructor
        Scanner scanner = new Scanner(System.in);

        int userInput = scanner.nextInt();
        System.out.println("Your number was: " + userInput);
        scanner.close(); // close the scanner
    }
}

Here is another example where we have a custom Regular Expression .useDelimiter(arg) while reading from a string.

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

System.out.println(s.nextInt()); // 1
System.out.println(s.nextInt()); // 2
System.out.println(s.next());    // red
System.out.println(s.next());    // blue

s.close(); // we close the input string

Constructors

It accpet various objects according to the official documentation.

  • some notable ones include InputStream (like System.in), File, Path
  • to get a file we use java.nio.file.Paths.get("path/to/file.txt"), see java.nio.file.

The next___() Methods

The scanner saves its pointer within the Readable and will only scan forwards, unless we .reset() the scanner back to the start.

They don't skip over tokens that don't match them and will throw an Exception.

The hasNext___() Methods

They allow us to check whether the next token in the scanner has a specific ___ data type that can be scanned.

  • the ___ can be replaced by the data types used in the next___() methods.

import java.nio.file.Paths;
import java.util.Scanner;

public class PrintingAFile {

    public static void main(String[] args) {
        try (Scanner scan = new Scanner(Paths.get("data.txt"))) {
            while (scan.hasNextLine()) {
                System.out.println(scan.nextLine());
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        
    }
}

References