Java User Input with Scanner

Java User Input with Scanner: A Complete Guide with Examples and Exercises

Java provides several ways to accept user input, and one of the most commonly used methods is the Scanner class. Scanner allows you to read different types of input from the user, such as strings, integers, and floating-point numbers. This guide will help you understand the Scanner class, how to use it to capture user input, and provide exercises to practice using it effectively.


Table of Contents

  1. What is the Scanner Class?
  2. Setting Up Scanner for User Input
  3. Reading Different Types of Input
  4. Handling Input Errors
  5. Closing the Scanner
  6. Exercises

1. What is the Scanner Class?

The Scanner class is part of the java.util package and provides methods to read data from various sources, including keyboard input, files, and strings. When working with user input, the Scanner class is often used in conjunction with System.in to capture keyboard input in the console.

Importing the Scanner Class

To use Scanner, you need to import it at the beginning of your Java program:

import java.util.Scanner;

2. Setting Up Scanner for User Input

The Scanner class reads input through different methods depending on the data type you want to capture. You first need to create a Scanner object that links to System.in, representing the console as the input source.

Example of Setting Up a Scanner

import java.util.Scanner;

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

        System.out.println("Enter your name:");
        String name = scanner.nextLine();  // Reads a string input from the user
        System.out.println("Hello, " + name + "!");

        scanner.close();  // Close the scanner to free resources
    }
}

In this example:

  • A Scanner object named scanner is created to read input from System.in.
  • scanner.nextLine() is used to read a line of text entered by the user.

3. Reading Different Types of Input

The Scanner class provides several methods to read various data types, including:

  • nextLine(): Reads a line of text (string)
  • next(): Reads a single word (string)
  • nextInt(): Reads an integer
  • nextDouble(): Reads a double (floating-point number)
  • nextFloat(): Reads a float
  • nextBoolean(): Reads a boolean (true/false)

Each of these methods is designed to capture a specific type of input from the user.

Example of Reading Different Types of Input

import java.util.Scanner;

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

        // Read a string
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

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

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

        // Output the collected information
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);

        scanner.close();
    }
}

In this example:

  • scanner.nextLine() reads a line of text.
  • scanner.nextInt() reads an integer.
  • scanner.nextDouble() reads a double.

4. Handling Input Errors

If a user enters input that doesn’t match the expected data type, a InputMismatchException will be thrown. To handle these cases, you can use a try-catch block or validate the input using Scanner’s hasNext<Type>() methods before attempting to read the value.

Example of Handling Input Errors with Validation

import java.util.Scanner;

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

        // Read an integer with validation
        System.out.print("Enter your age: ");
        if (scanner.hasNextInt()) {
            int age = scanner.nextInt();
            System.out.println("Your age is: " + age);
        } else {
            System.out.println("Invalid input! Please enter an integer.");
        }

        // Read a double with validation
        System.out.print("Enter your GPA: ");
        if (scanner.hasNextDouble()) {
            double gpa = scanner.nextDouble();
            System.out.println("Your GPA is: " + gpa);
        } else {
            System.out.println("Invalid input! Please enter a valid decimal number.");
        }

        scanner.close();
    }
}

In this example:

  • scanner.hasNextInt() checks if the next input is an integer.
  • scanner.hasNextDouble() checks if the next input is a double.
  • Using if-else allows you to validate input and provide a custom error message if the input is invalid.

5. Closing the Scanner

It’s essential to close the Scanner object after you’re done using it, especially in larger applications. This practice helps free system resources associated with the scanner. You can close the scanner by calling the close() method:

scanner.close();

Note: Avoid using a closed scanner object after calling close(), as it will cause an IllegalStateException.


6. Exercises

Here are some exercises to practice working with the Scanner class in Java.

Exercise 1: Basic User Input

Write a program that:

  1. Prompts the user to enter their first name.
  2. Prompts the user to enter their last name.
  3. Prints a greeting message, e.g., “Hello, [First Name] [Last Name]!”

Solution for Exercise 1

import java.util.Scanner;

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

        System.out.print("Enter your first name: ");
        String firstName = scanner.nextLine();

        System.out.print("Enter your last name: ");
        String lastName = scanner.nextLine();

        System.out.println("Hello, " + firstName + " " + lastName + "!");

        scanner.close();
    }
}

Exercise 2: Sum of Two Numbers

Write a program that:

  1. Prompts the user to enter two integer numbers.
  2. Calculates the sum of the numbers and displays the result.

Solution for Exercise 2

import java.util.Scanner;

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

        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        int sum = num1 + num2;
        System.out.println("The sum is: " + sum);

        scanner.close();
    }
}

Exercise 3: Area of a Rectangle

Write a program that:

  1. Prompts the user to enter the length and width of a rectangle.
  2. Calculates and prints the area of the rectangle.

Solution for Exercise 3

import java.util.Scanner;

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

        System.out.print("Enter the length of the rectangle: ");
        double length = scanner.nextDouble();

        System.out.print("Enter the width of the rectangle: ");
        double width = scanner.nextDouble();

        double area = length * width;
        System.out.println("The area of the rectangle is: " + area);

        scanner.close();
    }
}

Exercise 4: Age Validation with Error Handling

Write a program that:

  1. Prompts the user to enter their age.
  2. Checks if the input is an integer. If it is, display the age; if not, display an error message.

Solution for Exercise 4

import java.util.Scanner;

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

        System.out.print("Enter your age: ");
        if (scanner.hasNextInt()) {
            int age = scanner.nextInt();
            System.out.println("Your age is: " + age);
        } else {
            System.out.println("Invalid input! Please enter an integer for age.");
        }

        scanner.close();
    }
}

Exercise 5: Calculate BMI (Body Mass Index)

Write a program that:

  1. Prompts the user to enter their weight in kilograms and height in meters.
  2. Calculates their BMI using the formula: BMI = weight / (height * height).
  3. Displays the BMI result.

Solution for Exercise 5

import java.util.Scanner;

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

        System.out.print("Enter your weight in kg: ");
        double weight = scanner.nextDouble();

        System.out.print("Enter your height in meters: ");
        double height = scanner.nextDouble();

        double bmi = weight / (height * height);
        System.out.println("Your BMI is: " + bmi);

        scanner.close();
    }
}

Conclusion

The Scanner class in Java offers a straightforward and efficient way to capture user input for different data types. By understanding how to use Scanner and handling potential input errors,

you can build interactive Java applications that respond to user input. Practice the exercises above to reinforce your understanding of how to read user input with Scanner.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top