在Java中,有四种不同的方法可以在命令行环境(控制台)中读取用户的输入。
1.使用缓冲读取器类
这是JDK1中引入的Java经典输入方法。0.此方法用于包装系统。在打包在BufferedReader中的InputStreamReader中(标准输入流),我们可以在命令行中读取用户的输入。
- 输入被缓冲以有效读取。
- 包装代码很难记住。
实施:
JAVA
// Java program to demonstrate BufferedReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { // Enter data using BufferReader BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); // Printing the read line System.out.println(name); } } |
输入:
Geek
输出:
Geek
注:
要读取其他类型,我们使用Integer之类的函数。parseInt(),双精度。parseDouble()。要读取多个值,我们使用split()。
2.使用Scanner类
这可能是最受欢迎的输入方法。Scanner类的主要用途是使用正则表达式解析原语类型和字符串,但是,它也可以用于在命令行中读取用户的输入。
- 用于从标记化输入解析原语(nextInt()、nextFloat()、…)的便捷方法。
- 正则表达式可用于查找标记。
- 读取方法不同步
要查看更多差异,请参阅 这 文章
JAVA
// Java program to demonstrate working of Scanner in Java import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println( "You entered string " + s); int a = in.nextInt(); System.out.println( "You entered integer " + a); float b = in.nextFloat(); System.out.println( "You entered float " + b); // closing scanner in.close(); } } |
输入:
GeeksforGeeks123.4
输出:
You entered string GeeksforGeeksYou entered integer 12You entered float 3.4
3.使用控制台类
它已经成为从命令行读取用户输入的首选方式。此外,它还可以用于读取类似密码的输入,而无需回显用户输入的字符;也可以使用格式字符串语法(如System.out.printf())。
优势:
- 读取密码而不回显输入的字符。
- 阅读方法是同步的。
- 可以使用格式字符串语法。
- 不适用于非交互式环境(如IDE)。
JAVA
// Java program to demonstrate working of System.console() // Note that this program does not work on IDEs as // System.console() may require console public class Sample { public static void main(String[] args) { // Using Console to input data from user String name = System.console().readLine(); System.out.println( "You entered string " + name); } } |
输入:
GeeksforGeeks
输出:
You entered string GeeksforGeeks
4. 使用命令行参数
最常用的用户输入用于竞争编码。命令行参数以字符串格式存储。Integer类的parseInt方法将字符串参数转换为整数。类似地,在执行过程中也适用于float和其他。args[]的用法在这种输入形式中开始出现。信息传递发生在程序运行期间。命令行提供给args[]。这些程序必须在cmd上运行。
代码:
JAVA
// Program to check for command line arguments class Hello { public static void main(String[] args) { // check if length of args array is // greater than 0 if (args.length > 0 ) { System.out.println( "The command line arguments are:" ); // iterating the args array and printing // the command line arguments for (String val : args) System.out.println(val); } else System.out.println( "No command line " + "arguments found." ); } } |
命令行参数:
javac GFG1.javajava Main Hello World
输出:
The command line arguments are:HelloWorld
请参考 这 获取更快速的输入读取方法。
本文由 德拉杰·拉努 .如果你喜欢GeekSforgek并想投稿,你也可以使用“投稿”撰写文章。极客。组织或邮寄你的文章到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。