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

如何在 Java 中读取输入的数字和字母
Java 中有多种方法可以从控制台读取用户输入的数字和字母:
1. Scanner 类
Scanner 类提供了 nextInt() 和 nextLine() 方法,分别用于读取数字和字符串。
立即学习“Java免费学习笔记(深入)”;
<code class="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();
}
}</code>2. BufferedReader 类
BufferedReader 类提供了 readLine() 方法,用于读取一行文本。
<code class="java">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();
}
}</code>3. Console 类
Console 类(在 Java 11 中引入)提供了一个更简洁的方式来读取输入。
<code class="java">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();
}
}</code>注意:
以上就是java怎么读取输入的数字和字母的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号