Reputation: 1
this is the code I am dealing with
public class NameTag
{
public static void main (String[] args)
{
System.out.println ();
System.out.println (" " + args[0]);
System.out.println ("My name is " + args[1]);
System.out.println ();
}
}
this is the error that keeps showing each time I try to run the program java.lang.ArrayIndexOutOfBoundsException: 0 at NameTag.main(NameTag.java:6)
I am using BlueJ Version 3.1.0 *I have no idea how to fix this error, I have tried many different things but nothing is working. Please help.*
Upvotes: 0
Views: 457
Reputation: 1615
Check for the length of the array before doing any other operations.
public static void main (String[] args)
{
if(args.length > 1) {
System.out.println ();
System.out.println (" " + args[0]);
System.out.println ("My name is " + args[1]);
System.out.println ();
}
}
Upvotes: 1
Reputation: 104
On blueJ, when you run, make sure you enter your input in the correct way and not empty. It will take your input and evaluate args[0] and args[1] from the input. It throws the exception when it can't find any argument.
Upvotes: 0
Reputation: 8815
That means you haven't passed any arguments to the program at execution. Therefore, accessing args[0]
and args[1]
leads to the ArrayIndexOutOfBoundsException
. http://www.bluej.org/help/archive.html#tip9 explains how to pass command line arguments to BlueJ. To save you the trouble of following the link, pass the following parameter to main:
{ "foo", "bar" }
to have the String "foo" in args[0]
and "bar" in args[1]
. Also, it's good practice to check the length of the args
array before doing anything with it, to make sure that arguments have indeed been passed.
Upvotes: 2