public class Main {
public static void main(String[] args) {
args = new String[]{"0 0 1 1"};
}
}
我想使用 Scanner
从控制台初始化 args
。可能吗?
最佳答案
args
包含调用时传递给 Java 程序的命令行参数。
例如,如果我像这样创建 PrintArgs
类:
public class PrintArgs {
public static void main (String[] args) {
for (String s: args) {// loop through args array
System.out.println(s); // print out every String
}
}
}
我现在可以运行 PrintArgs
并将 Strings
传递给 args
,例如在我写的命令行上:
$java PrintArgs First Second Third
因此,它将在控制台上打印出来:
First
Second
Third
因此,您不需要 Scanner
来读取 String[]args
数组。
此外,如果您想将文件路径作为字符串参数传递给 args
,然后使用 Scanner
从中读取,您可以这样做:
public class ReadFileUsingScanner{
public static void main (String[] args) {
try {
File f = new File(args[0]); // suppose you passed the file path as first String
Scanner input = new Scanner(f);
while (input.hasNextLine()) { // loop through every line
System.out.println(input.nextLine()); // print it out
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
然后运行 ReadFileUsingScanner
,例如:
$java ReadFileUsingScanner someFilePath.txt
关于java - 使用扫描仪 JAVA 初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44122163/