简体   繁体   中英

How to pass command-line arguments?

I get the above error when I try to compile this simple program:

/* @author 
 * This program expects two command-line arguments
 * -- a person's first name and last name.
 * For example:
 * C:\Mywork> java Greetin Annabel Lee
 */
public class Greetin
{
    public static void main(String[] args)
    {
        String firstName = args[0];
        String lastName = args[1];
        System.out.println("Hello, " + firstName + " " + lastName);
        System.out.println("Congratulations on your second program!");
    }
}

From looking at other questions, I understand the error has something to do with args == 0 and 0 being greater than the number, but I don't know how to fix the problem for this case. Is there any way the error is also identified as being caused by the void ?

My guess is there aren't any args supplied to your program. Good convention is to make sure the user inputs the expected amount of args, else die. In your case:

if( args.length != 2 ){
    System.out.println("usage: Greetin <firstName> <lastName>");
}
else{
    String firstName = args[0];
    String lastName = args[1];
    System.out.println("Hello, " + firstName + " " + lastName);
    System.out.println("Congratulations on your second program!");
}

Also, make sure you type: java Greetin Annabel Lee after you compile to properly set the arguments.

You are probably not passing two command-line arguments to your program. The error is telling you that the array args doesn't have any elements because index 0 is out of the valid bounds. Make sure to pass the arguments when running your program.

java Greetin Annabel Lee

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