简体   繁体   English

使用扫描程序JAVA初始化数组

[英]Array initializing with scanner JAVA

public class Main {
   public static void main(String[] args) {
      args = new String[]{"0 0 1 1"};
   }
}

I would like to initialize args from console using Scanner . 我想使用Scanner从控制台初始化args Is it possible? 可能吗?

args contains the command-line arguments passed to the Java program upon invocation. args包含调用时传递给Java程序的命令行参数。

For example if I create PrintArgs class like this: 例如,如果我像这样创建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
        }
    }
}

I can now run PrintArgs and pass Strings to args , for example on the command-line I write: 我现在可以运行PrintArgs并将Strings传递给args ,例如在我编写的命令行上:

$java PrintArgs First Second Third

So, it will print out on the console: 因此,它将在控制台上打印出来:

First
Second
Third

Accordingly, you don't need Scanner to read from String[]args array. 因此,您不需要ScannerString[]args数组中读取。

Furthermore, If you want to pass a file path as a String argument to args , then use the Scanner to read from it, you can do for example: 此外,如果要将文件路径作为String参数传递给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();
        }
    }
} 

Then you run ReadFileUsingScanner for example like this: 然后你运行ReadFileUsingScanner ,例如:

$java ReadFileUsingScanner someFilePath.txt

args gets initialised by java when you your run the program using java command, eg: java Main.class abc 当你使用java命令运行程序时, args会被java初始化,例如: java Main.class abc

So, it's not something we initialise inside the program. 所以,这不是我们在程序中初始化的东西。 Although you can re-initialise the args inside main method, you should not do it as it (a) loses its previous value and (b) works against the immutability of arguments. 虽然你可以重新初始化main方法中的args ,但你不应该这样做(a)失去它以前的值,(b)不利于参数的不变性。

You could probably create a new array and ask the user for inputs, eg: 您可以创建一个新array并询问用户输入,例如:

String[] array = new String[5];
Scanner scanner = new Scanner(System.in);
System.out.println("Enter "+ array.length + " inputs :" );
for(int i = 0; i < array.length ; i++){
    array[i] = scanner.nextLine();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM