Reputation: 119
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
?
Upvotes: 1
Views: 489
Reputation: 2396
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.
Upvotes: 2
Reputation: 36522
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
Upvotes: 1