Java Scanner输入:如何获取用户输入,从控制台读取数据

When programming, we often need to interact with users—for example, asking for their name, age, or calculating numbers they provide. Java provides the Scanner class to easily read user input from the console. This article will teach you how to use the Scanner class to obtain user data in the simplest way, step by step.

I. What is Scanner?

Scanner is a utility class in the Java standard library, located in the java.util package. It helps us read data from the console (keyboard) or files, such as integers, strings, and decimals. For beginners, the most common use is reading input from the console.

II. How to Use Scanner?

Using Scanner requires three steps: Import the packageCreate an objectCall methods to read data.

1. Import the Scanner Class

First, tell Java you want to use Scanner by importing the class at the beginning of your code:

import java.util.Scanner; // Import the Scanner class, must be placed at the top of the code

2. Create a Scanner Object

The Scanner object listens for console input and is created using System.in (standard input stream, i.e., the keyboard):

Scanner scanner = new Scanner(System.in); // Create a Scanner object

3. Call Methods to Read Data

After creating the object, use different methods of scanner to read data of different types, such as:
- nextInt(): Reads an integer (type int).
- nextDouble(): Reads a decimal (type double).
- nextLine(): Reads an entire line of text (including spaces).
- next(): Reads a single word (stops at spaces or newlines).

III. Reading Different Types of Data

Let’s look at examples of reading common data types:

1. Reading an Integer (int)

Suppose you want the user to input their age:

import java.util.Scanner;

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

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

        // Output the result
        System.out.println("You entered the age: " + age);

        // Close the Scanner (optional but recommended)
        scanner.close();
    }
}

Running Effect:

Please enter your age: 20
You entered the age: 20

2. Reading a String

There is a significant difference between next() and nextLine() for reading strings:
- next(): Stops at spaces or newlines, so it only reads a single word (e.g., “Alice”, “Bob”).
- nextLine(): Reads the entire line of text (including spaces) until the user presses Enter (suitable for names, addresses, etc., where spaces are needed).

Example 1: Using next() to Read a String

System.out.print("Please enter your name: ");
String name = scanner.next(); // Reads only "John" if the input is "John Doe"

Example 2: Using nextLine() to Read a String

System.out.print("Please enter your name: ");
String name = scanner.nextLine(); // Reads "John Doe" if the input is "John Doe"

3. Reading a Decimal (double)

To read decimals (e.g., height or weight):

System.out.print("Please enter your height (in meters): ");
double height = scanner.nextDouble();
System.out.println("Your height is: " + height + " meters");

IV. Complete Example: Reading Multiple Data Types

Suppose you want to create a program that asks for a name, age, and height, then outputs the information:

import java.util.Scanner;

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

        // Read name (using nextLine to avoid space issues)
        System.out.print("Please enter your name: ");
        String name = scanner.nextLine();

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

        // Read height (decimal)
        System.out.print("Please enter your height (in meters): ");
        double height = scanner.nextDouble();

        // Output the information
        System.out.println("\nYour information:");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height + " meters");

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

Running Effect:

Please enter your name: Zhang San
Please enter your age: 20
Please enter your height (in meters): 1.75

Your information:
Name: Zhang San
Age: 20
Height: 1.75 meters

V. Common Issues and Solutions

1. Input Mismatch Exception

If the user enters a data type that doesn’t match what the program expects (e.g., entering letters when an integer is required), an InputMismatchException is thrown.
Solution: Ensure the input type matches the expected type, or use try-catch to handle exceptions (advanced topic; beginners can focus on input correctness first).

2. Buffer Residue Problem

If you use nextInt() to read an integer and then nextLine() to read a string, you may get an empty string.
Reason: After nextInt(), a newline character remains in the buffer, and nextLine() reads this newline, resulting in an empty string.
Solution: Add scanner.nextLine() after nextInt() to clear the buffer:

System.out.print("Please enter your age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume the remaining newline character

System.out.print("Please enter your name: ");
String name = scanner.nextLine(); // Now reads the user's actual input

VI. Summary

Scanner is a fundamental input tool in Java. The core steps are:
1. Import java.util.Scanner.
2. Create a Scanner object: scanner = new Scanner(System.in).
3. Call methods like nextInt(), nextLine(), or nextDouble() to read data based on the type.
4. Close the scanner with scanner.close() (releases resources).

With simple examples, you’ll quickly master reading user input from the console!

Xiaoye