1

I'm just a beginner to write programs in Java. How to pass the arguments (Array of strings) to the main method? I'm using Eclipse as an IDE

public static void main(String[] args) {
    // TODO Auto-generated method stub
    if (args[0].equals("-h"))
        System.out.print("Hello,");
    else if (args[0].equals("-g"))
        System.out.print("Goodbye,");

    // print the other command-line arguments
    for (int i = 1; i < args.length; i++)
        System.out.print(" " + args[i]);

    System.out.println("!");
}
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
Aishu
  • 1,310
  • 6
  • 28
  • 52

3 Answers3

4

Run > Run Configurations > Java Application > Arguments > Program arguments

Arguments Result


Also, make sure your code works when no arguments are passed, don't just directly pick values from array.

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        if (args != null && args.length > 0) {
            if (args[0].equals("-h"))
                System.out.print("Hello,");
            else if (args[0].equals("-g"))
                System.out.print("Goodbye,");

            // print the other command-line arguments
            for (int i = 1; i < args.length; i++)
                System.out.print(" " + args[i]);

        } else{
            System.out.print("No Arguments passed");
        }
        System.out.println("!");
    }
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
1

You can pass arguments in Run Configurations -> Java Application -> Arguments -> Program arguments

Link :- http://www.cs.colostate.edu/helpdocs/eclipseCommLineArgs.html

Jaiprakash
  • 599
  • 2
  • 7
  • 2
    That website looks like it hasn't been updated since 1998. – Michael Markidis Jun 22 '16 at 07:14
  • It still provides the basic overview which is used to pass the arguments. You can also refer to http://stackoverflow.com/questions/19646719/eclipse-command-line-arguments/19648592 – Jaiprakash Jun 22 '16 at 07:16
0

right click | run as | open Run Dialog |(x)=Arguments

then put you args

xenteros
  • 15,586
  • 12
  • 56
  • 91
biubiu
  • 1
  • 1