Java User Input with Scanner: Overview and Examples

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Introduce Java User Input (Scanner) and give examples

Answer:

In Java, the Scanner class is a part of the java.util package and is used to obtain input from various sources, including user input from the console. It provides methods to read different types of data, such as strings, integers, and floating-point numbers.

How to Use the Scanner Class

  1. Import the Scanner Class: You need to import the java.util.Scanner package at the beginning of your Java program.
  2. Create a Scanner Object: Instantiate a Scanner object to read input.
  3. Read Input: Use the appropriate methods to read different types of data.
  4. Close the Scanner: It's a good practice to close the Scanner object when you're done to free up resources.

Example Code

Here’s a simple example demonstrating how to use the Scanner class to read user input:

import java.util.Scanner;

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

        // Prompt the user for their name
        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Read a string input

        // Prompt the user for their age
        System.out.print("Enter your age: ");
        int age = scanner.nextInt(); // Read an integer input

        // Prompt the user for their height
        System.out.print("Enter your height in meters: ");
        double height = scanner.nextDouble(); // Read a double input

        // Display the collected information
        System.out.println("Hello, " + name + "!");
        System.out.println("You are " + age + " years old.");
        System.out.println("Your height is " + height + " meters.");

        // Close the scanner
        scanner.close();
    }
}

Explanation of the Example

  1. Import Statement: import java.util.Scanner; imports the Scanner class.
  2. Creating a Scanner Object: Scanner scanner = new Scanner(System.in); creates a new Scanner object that reads from the standard input (keyboard).
  3. Reading Input:
    • scanner.nextLine() reads a line of text (string).
    • scanner.nextInt() reads an integer.
    • scanner.nextDouble() reads a double (floating-point number).
  4. Output: The program prints the user's name, age, and height.
  5. Closing the Scanner: scanner.close(); is called to close the Scanner object, which is a good practice to prevent resource leaks.

Additional Methods of Scanner

The Scanner class provides several other methods to read different types of input:

  • next(): Reads the next token (word) as a string.
  • nextBoolean(): Reads the next token as a boolean.
  • nextByte(): Reads the next token as a byte.
  • nextShort(): Reads the next token as a short.
  • nextLong(): Reads the next token as a long.
  • nextFloat(): Reads the next token as a float.

Example of Reading Multiple Inputs

Here’s another example that demonstrates reading multiple inputs in a loop:

import java.util.Scanner;

public class MultipleInputsExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("How many numbers do you want to enter? ");
        int count = scanner.nextInt();
        
        int sum = 0;
        
        for (int i = 0; i < count; i++) {
            System.out.print("Enter number " + (i + 1) + ": ");
            int number = scanner.nextInt();
            sum += number; // Add the number to the sum
        }
        
        System.out.println("The sum of the entered numbers is: " + sum);
        
        scanner.close();
    }
}

In this example, the program asks the user how many numbers they want to enter, reads that many integers, and calculates their sum.

Conclusion

The Scanner class is a powerful and flexible way to handle user input in Java. By using it, you can easily read various types of data from the console, making it a fundamental tool for interactive Java applications.