0

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.*

3
  • 3
    You need to pass some arguments (at least 2 with your code) when running your main method. Commented Jan 16, 2014 at 18:53
  • are you aware what the purpose of the args array is and are you doing what needs to be done to fill it when you run the program? Commented Jan 16, 2014 at 18:53
  • You need to run the program with at least two arguments on the command line. I'm not familiar with BlueJ so I don't know how to run programs and pass arguments. Commented Jan 16, 2014 at 18:54

3 Answers 3

2

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.

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

Comments

1

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 ();
    }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.