简体   繁体   中英

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 . Is it possible?

args contains the command-line arguments passed to the Java program upon invocation.

For example if I create PrintArgs class like this:

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:

$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.

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:

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:

$java ReadFileUsingScanner someFilePath.txt

args gets initialised by java when you your run the program using java command, eg: 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.

You could probably create a new array and ask the user for inputs, eg:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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