Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ArrayIndexOutOfBoundsException: 0

I am learning java using a book. There is this exercise that I can't get to work properly. It adds two doubles using the java class Double. When I try to run this code in Eclipse it gives me the error in the title.

public static void main(String[] args) {

    Double d1 = Double.valueOf(args[0]);
    Double d2 = Double.valueOf(args[1]);
    double result = d1.doubleValue() + d2.doubleValue();
    System.out.println(args[0] + "+" + args[1] + "=" + result);

}
like image 627
pg2014 Avatar asked May 04 '14 13:05

pg2014


1 Answers

Problem

This ArrayIndexOutOfBoundsException: 0 means that the index 0 is not a valid index for your array args[], which in turn means that your array is empty.

In this particular case of a main() method, it means that no argument was passed on to your program on the command line.

Possible solutions

  • If you're running your program from the command line, don't forget to pass 2 arguments in the command.

  • If you're running your program in Eclipse, you should set the command line arguments in the run configuration. Go to Run > Run configurations... and then choose the Arguments tab for your run configuration and add some arguments in the program arguments area.

Note that you should handle the case where not enough arguments are given, with something like this at the beginning of your main method:

if (args.length < 2) {
    System.err.println("Not enough arguments received.");
    return;
}

This would fail gracefully instead of making your program crash.

like image 115
Joffrey Avatar answered Nov 11 '22 20:11

Joffrey