How to read a long integer input using Scanner in Java?

JavaJavaBeginner
Practice Now

Introduction

In this tutorial, we will explore the process of reading long integer input using the Java Scanner class. We will cover the essential steps and techniques to ensure accurate and reliable data input, as well as how to handle common numeric input exceptions that may arise during the process.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java/ObjectOrientedandAdvancedConceptsGroup -.-> java/exceptions("`Exceptions`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") subgraph Lab Skills java/exceptions -.-> lab-417653{{"`How to read a long integer input using Scanner in Java?`"}} java/user_input -.-> lab-417653{{"`How to read a long integer input using Scanner in Java?`"}} java/wrapper_classes -.-> lab-417653{{"`How to read a long integer input using Scanner in Java?`"}} end

Introduction to Java Scanner

In Java, the Scanner class is a powerful tool for reading input from various sources, including the console, files, and network connections. It provides a simple and efficient way to parse and interpret different types of input data, including integers, floating-point numbers, strings, and more.

The Scanner class is part of the java.util package, and it can be imported using the following statement:

import java.util.Scanner;

To create a Scanner object and use it to read input, you can follow these steps:

  1. Create a new Scanner object, passing the input source as a parameter:

    Scanner scanner = new Scanner(System.in);

    In this example, we create a Scanner object that reads input from the console (standard input).

  2. Use the appropriate methods provided by the Scanner class to read different types of input. For example, to read an integer, you can use the nextInt() method:

    int number = scanner.nextInt();

    The Scanner class provides various other methods, such as nextDouble(), nextLine(), nextBoolean(), and more, to read different data types.

  3. Remember to close the Scanner object when you're done using it to free up system resources:

    scanner.close();

By using the Scanner class, you can easily read and process user input in your Java applications, making them more interactive and user-friendly.

Reading Long Integers with Scanner

While the nextInt() method of the Scanner class is suitable for reading standard-sized integers, it may not be able to handle very large integer values, such as those that exceed the range of the int data type in Java. In such cases, you can use the nextLong() method to read long integer values.

The long data type in Java can store integer values in the range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, which is much larger than the range of the int data type (-2,147,483,648 to 2,147,483,647).

Here's an example of how to use the nextLong() method to read a long integer input:

import java.util.Scanner;

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

        System.out.print("Enter a long integer: ");
        long longNumber = scanner.nextLong();

        System.out.println("You entered: " + longNumber);

        scanner.close();
    }
}

In this example, we create a Scanner object and use the nextLong() method to read the long integer input from the user. The input is then stored in the longNumber variable and printed to the console.

Remember to handle potential exceptions that may occur when reading input, such as InputMismatchException if the user enters a non-numeric value. We'll cover that in the next section.

Handling Numeric Input Exceptions

When reading numeric input using the Scanner class, it's important to handle potential exceptions that may occur. One common exception is the InputMismatchException, which is thrown when the user enters a non-numeric value.

To handle these exceptions, you can use a try-catch block to catch the exception and provide appropriate error handling. Here's an example:

import java.util.InputMismatchException;
import java.util.Scanner;

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

        try {
            System.out.print("Enter a long integer: ");
            long longNumber = scanner.nextLong();
            System.out.println("You entered: " + longNumber);
        } catch (InputMismatchException e) {
            System.out.println("Error: Invalid input. Please enter a valid long integer.");
        } finally {
            scanner.close();
        }
    }
}

In this example, we wrap the scanner.nextLong() call in a try block. If the user enters a non-numeric value, the InputMismatchException is caught, and we print an error message. Finally, we close the Scanner object in the finally block to ensure that system resources are properly released.

By handling exceptions, you can make your Java applications more robust and provide a better user experience by gracefully handling unexpected input.

Additionally, you can use a loop to repeatedly prompt the user for input until a valid long integer is entered. Here's an example:

import java.util.InputMismatchException;
import java.util.Scanner;

public class NumericInputException {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long longNumber;
        boolean validInput = false;

        while (!validInput) {
            try {
                System.out.print("Enter a long integer: ");
                longNumber = scanner.nextLong();
                validInput = true;
                System.out.println("You entered: " + longNumber);
            } catch (InputMismatchException e) {
                System.out.println("Error: Invalid input. Please enter a valid long integer.");
                scanner.nextLine(); // Clear the input buffer
            }
        }

        scanner.close();
    }
}

In this example, we use a while loop to repeatedly prompt the user for input until a valid long integer is entered. The scanner.nextLine() call is used to clear the input buffer after an InputMismatchException is caught, allowing the user to enter a new value.

By handling exceptions and providing a robust input validation process, you can ensure that your Java applications can gracefully handle a variety of user inputs and provide a better overall user experience.

Summary

By the end of this tutorial, you will have a strong understanding of how to read long integer input using the Java Scanner class, as well as the ability to handle any numeric input exceptions that may occur. This knowledge will be invaluable in your Java programming journey, allowing you to build robust and user-friendly applications.

Other Java Tutorials you may like