如何在 Java 中读取输入的数字和字母?使用 Scanner 类读取数字(nextInt())和字符串(nextLine())。使用 BufferedReader 类读取一行文本并解析数字(parseInt())。使用 Console 类读取数字(nextInt())和字符串(readLine())。

如何在 Java 中读取输入的数字和字母
Java 中有多种方法可以从控制台读取用户输入的数字和字母:
1. Scanner 类
Scanner 类提供了 nextInt() 和 nextLine() 方法,分别用于读取数字和字符串。
立即学习“Java免费学习笔记(深入)”;
import java.util.Scanner;
public class ReadInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取数字
int number = scanner.nextInt();
// 读取字符串(包括空格)
String inputString = scanner.nextLine();
}
}2. BufferedReader 类
BufferedReader 类提供了 readLine() 方法,用于读取一行文本。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadInput {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// 读取数字
int number = Integer.parseInt(reader.readLine());
// 读取字符串(不包括换行符)
String inputString = reader.readLine();
}
}3. Console 类
Console 类(在 Java 11 中引入)提供了一个更简洁的方式来读取输入。
import java.io.Console;
public class ReadInput {
public static void main(String[] args) {
Console console = System.console();
// 读取数字
int number = console.reader().nextInt();
// 读取字符串(包括空格)
String inputString = console.reader().readLine();
}
}注意:
- 所有方法都会阻塞,直到用户输入数据并按 Enter 键。
- 对于数字输入,确保检查数字格式是否正确,例如使用 Integer.parseInt() 或 Integer.valueOf() 方法。











