如何在 Java 中读取输入的数字和字母?使用 Scanner 类读取数字(nextInt())和字符串(nextLine())。使用 BufferedReader 类读取一行文本并解析数字(parseInt())。使用 Console 类读取数字(nextInt())和字符串(readLine())。
如何在 Java 中读取输入的数字和字母
Java 中有多种方法可以从控制台读取用户输入的数字和字母:
1. Scanner 类
Scanner 类提供了 nextInt() 和 nextLine() 方法,分别用于读取数字和字符串。
<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中文网其他相关文章!