How to pass parameters to the args array in this public static void main(String[] args)

How to pass parameters to the args array in this public static void main(String[] args)

To pass arguments to an array public static void main(String[] args)in args, you can append arguments when running a Java program from the command line.

Here are two common methods:

  1. Manually enter parameters on the command line:

    We first need to enter the folder where this class is located

    Run a Java program by entering a command in the command prompt or terminal similar to the following format:

    java YourClassName arg1 arg2 arg3 ...
    

    Among them YourClassNameis the name of the Java class you want to execute, and the following arg1, arg2, arg3etc. are the parameters you want to pass to mainthe method.

    important point

    This command line executes the java class and does not support Chinese. So do not include Chinese in your code

  2. Configure parameters in the integrated development environment (IDE):
    If you are using an integrated development environment (such as Eclipse, IntelliJ IDEA, etc.), you can set parameters in the corresponding configuration.

    • In Eclipse: Right-click the project, select "Run As" -> "Run Configurations", and then fill in the required parameters in the "Arguments" tab.
    • In IntelliJ IDEA: Click "Run" -> "Edit Configurations" in the top menu, and then add parameters in the "Program arguments" input box.

Whichever method you choose, the parameters will be stored as strings in argsan array and can be used in your program.

public class test {
    
    
    public static void main(String[] args) {
    
    
        for (int i = 0; i < args.length; i++) {
    
    
            String arg = args[i];
            if (arg.equals("-h")) {
    
    
                arg = "hellp";
            } else if (arg.equals("-g")) {
    
    
                arg = "Goodbye";
            }
            System.out.println(arg);
        }
    }
}
Goodbye
cruel
world

Guess you like

Origin blog.csdn.net/everything_study/article/details/132291124