Java Scanner Class

What is the Java Scanner Class?

The Java Scanner class is a component of the java.util library. Its purpose is to extract data types, strings and regular expressions from an input stream. This class offers an approach to managing input from diverse origins such as keyboards, files or network connections. It presents functions for interpreting data types like integers, floating point numbers, booleans and strings serving as a flexible instrument, for managing user input and manipulating data within Java applications.

Why is the Scanner Class Important in Java Programming?

The Scanner class plays a role as it streamlines the task of collecting user input analyzing text and accessing various data origins. Through functions such as nextLine() nextInt() and nextDouble() programmers can smoothly request user inputs. Fetch the associated data facilitating interactive software. This class also aids in interpreting text transforming it into data types and reading from diverse sources like files or standard input. Moreover it facilitates tokenizing input, for data extraction and processing.

Using the Scanner Class to Get User Input

To use the Scanner class for obtaining user input, you first create an instance of the class with System.in as the data source. Here's an example:

Scanner scanner = new Scanner(System.in);

You have the choice to establish a separator by utilizing the setDelimiter() function. Once you have initialized the Scanner object you can collect input from users through functions like next() and nextLine(). Remember to offer an instruction before accepting input to guide users on what is required. The Scanner object can transform the input into the specified data type using functions such, as nextInt() nextDouble() or nextBoolean().

How to Create a Scanner Object

To create a Scanner object, first import the java.util.Scanner package. Then, instantiate the Scanner object:

Scanner scanner = new Scanner(System.in);

To begin you can set up a Scanner object to take input from the keyboard. Additionally you have the option to establish Scanner objects for reading from sources such, as an InputStream, a File or a String. As an illustration —

  • From an InputStream:
InputStream inputStream = new FileInputStream("example.txt");
Scanner scanner = new Scanner(inputStream);
  • From a File:
File file = new File("example.txt");
Scanner scanner = new Scanner(file);
  • From a String:
String input = "Hello, world!";
Scanner scanner = new Scanner(input);

The Scanner typically uses spaces to values but you have the option to set a unique separation pattern by utilizing the useDelimiter function.

Reading Input from Standard Input Stream

To read input from the standard input stream, import the Scanner class and create an instance:

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
  • Read an integer: int num = scanner.nextInt();
  • Read a line of text: String text = scanner.nextLine();
  • Read a word: String word = scanner.next();

Use the hasNextInt() method to check if the next input is an integer before reading it:

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

Closing the Scanner Object

It's crucial to close the Scanner object to free up system resources and avoid memory leaks. Simply call the close() method to properly close the Scanner.

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Code to read and process input
        scanner.close(); // Closing the Scanner object
    }
}

Not properly closing the Scanner could result in resources being left open and causing issues.

Working with Primitive Types

Dealing with data types entails working with fundamental data categories such as whole numbers, decimal numbers, letters and true/false values. This encompasses executing tasks setting values contrasting values and converting between types. Grasping the methods to manage these categories is crucial, for crafting code.

Reading Different Primitive Types Using Scanner

The Scanner class provides methods to read different primitive types:

  1. nextBoolean(): Reads a boolean value (true or false).
  2. nextByte(): Reads a byte value.
  3. nextDouble(): Reads a double value.
  4. nextFloat(): Reads a float value.

These methods make it easy to handle various types of user input.

Handling Exceptions When Parsing Input

When converting input to data types it's crucial to address any exceptions that may arise to avoid issues. Employ try catch mechanisms to handle exceptions such as NumberFormatException in case the input is not valid. This enhances the programs resilience and safeguards, against failures.

Tokenizing Input with Scanner

Breaking down the input, into units known as tokens is a helpful way to handle each element independently. The Scanner class can segment the input into tokens using custom delimiters or regular expressions.

Using Delimiters to Tokenize Input

To tokenize input using a custom delimiter, use the useDelimiter() method:

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");

This method sets a custom delimiter pattern for splitting the input into tokens.

Splitting Input into Tokens Using Regular Expressions

Regular expressions can be used with the Scanner class to split input into tokens. Set the delimiter using useDelimiter() with a regular expression pattern. For example:

scanner.useDelimiter("[,\\s]+");

This pattern splits the input based on spaces and commas. Use methods like next() to read the tokens one by one.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate