views:

137

answers:

3

I am passing a command line argument using Netbeans but I get an ArrayIndexOutOfBoundsException.

My code is:

public class CmdLineArgumentPassing

{

      public static void main(String args[])
      {        
         System.out.println("Count : " + args.length);

         System.out.println("i : "+args[0]);
      }
} 

The output is:

Count : 0

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
+1  A: 

As your output is Count : 0 then the args array has a length of 0 which means no arguments are being passed.

When you try to access the first argument using arg[0] you get an Exception as you are trying to get a member of the array which does not exist. In this case you're trying to get the first member of an empty array. Remember array indexes start at 0 and go to length - 1.

As args is empty it means the problem is with Netbeans passing your arguments not with your code, so my guess is that Netbeans is not configured properly.

Dave Webb
+1  A: 

Right mouse click on the project, select Properties, go to the Run page, add the command line arguments.

TofuBeer
Ya I already did this and my value is 12 there.
Samurai
If I set that project as main project and I run using F6 I got the output. Here in this project I have this file only and also set this class as main class. Then run using shift+F6 i cant get output.
Samurai
Right mouse click on Project and select Run (or F6, but the Run way doesn't require the project to be the main one...). If you are testing or just trying to run a class directly you will not be able to pass it arguments.
TofuBeer
In the project properties, be careful to fill in the program arguments in the 'Arguments' field, not in 'VM Options'.
OliBlogger
A: 

Click on Final proj and run and not the main project for netbeans 6.9. U will get the answer.

akshay