更新時間:2022-06-09 11:15:42 來源:動力節點 瀏覽1239次
在 Java 中,有四種不同的方式可以在命令行環境(控制臺)中讀取用戶的輸入。
這是Java經典的取輸入方式,在JDK1.0中引入。此方法通過將 System.in(標準輸入流)包裝在 InputStreamReader 中來使用,InputStreamReader 包裝在 BufferedReader 中,我們可以在命令行中讀取用戶的輸入。
輸入被緩沖以實現高效讀取。
包裝代碼很難記住。
執行:
// 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);
}
}
輸入:
動力節點
輸出:
輔助空間:O(1)
動力節點
這可能是接受輸入的最首選方法。Scanner 類的主要目的是使用正則表達式解析原始類型和字符串,但是,它也可用于在命令行中讀取用戶的輸入。
從標記化輸入中解析基元(nextInt()、nextFloat()、...)的便捷方法。
正則表達式可用于查找標記。
閱讀方式不同步
// 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);
}
}
輸入:
GeeksforGeeks
12
3.4
輸出:
您輸入了字符串 GeeksforGeeks
您輸入了整數 12
你輸入了 float 3.4
它已成為從命令行讀取用戶輸入的首選方式。此外,它可以用于讀取類似密碼的輸入,而不用回顯用戶輸入的字符;也可以使用格式字符串語法(如 System.out.printf())。
優點:
讀取密碼而不回顯輸入的字符。
讀取方法是同步的。
可以使用格式字符串語法。
不適用于非交互環境(例如 IDE)。
// 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
輸出:
您輸入了字符串 GeeksforGeeks
最常用于競爭性編碼的用戶輸入。命令行參數以字符串格式存儲。Integer 類的 parseInt 方法將字符串參數轉換為 Integer。同樣,對于執行期間的浮動和其他。args[] 的用法出現在這種輸入形式中。信息的傳遞發生在程序運行期間。命令行提供給 args[]。這些程序必須在 cmd 上運行。
代碼:
// 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.java
java Main Hello World
輸出:
命令行參數是:
你好
世界
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習