0

I am a beginner and using Java arrays for the first time. When I output my code I get this error. There is no errors in my actual code, so I do not see where the problem is in my code.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0           
at sumdouble.Sumdouble.main(Sumdouble.java:24)

Here is my code

package sumdouble;


public class Sumdouble {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
 double sum = 0;
 int number = 1;

 double array[] = new double [5];
 for (number  = 0; number < 5; number++)
 {
     array[number] = Double.parseDouble(args[number]);
     System.out.println("The" +number+ "argument value is: " +array[number]);

     for(double numb: array)
     {
         sum = sum + numb;

     }
 }System.out.printf("Sum of all numbers = %2f", sum);
    // TODO code application logic here
}

}
henna994
  • 13
  • 4

2 Answers2

0

You access args[number], but you did not pass any arguments when you started the program. The args array has length 0. Therefore, access to args[0] is causing an ArrayIndexOutOfBoundsException.

Henry
  • 42,982
  • 7
  • 68
  • 84
  • How would I ensure that the array doesn't have length 0? I know the problem lies in the command line, but I am so new to this, that I have a hard time seeing how to make it work – henna994 Jun 17 '17 at 16:50
  • This depends on how you start your program. Do you run from the command line or from an IDE? Which IDE do you use? – Henry Jun 17 '17 at 17:02
  • I am using NetBeans 8.2 – henna994 Jun 17 '17 at 17:06
  • I cannot help with this one. Try to find out how to specify command line parameters when starting programs. – Henry Jun 17 '17 at 17:49
0

The error happen at the very first iteration of your loop. You access args which is an array that gets filled with the so called command-line arguments. If you don't pass any, that array is empty, and that is why you get that error.

Take a look at the official documentation to learn of to pass command line argument to your java applications here. It cannot hurt =)

If you are using eclipse take a look here

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
  • So how would I pass it to ensure my array is not empty. Would I have to use a different command-line argument? – henna994 Jun 17 '17 at 16:19