1

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?

8
  • Are you passing two arguments when you run the program? Which is line 12? Commented Aug 28, 2012 at 2:17
  • line 12 is the String firstName = args[0]; Commented Aug 28, 2012 at 2:26
  • I guess I'm passing two argument b/c of the args[0] and args[1] firstname and lastname, respectively. Commented Aug 28, 2012 at 2:27
  • You're expecting two arguments. This doesn't mean you are necessarily passing two arguments when running the class. Are you definitely using java Greetin Annabel Lee as you have in your comment? Commented Aug 28, 2012 at 2:36
  • So how do I pass two arguments, is that why the error is occurring? Yes, I'm using java Greeting, Annabel Lee is just and example input. Commented Aug 28, 2012 at 2:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the fix helped, I'm beginning in java, so some of terminology is a bit foreign but I'll get used to it with some studying.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.