7

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

}
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
pg2014
  • 89
  • 1
  • 1
  • 3
  • 9
    Are you passing command line arguments ie value for `args[0]` and `args[1]`? – Pradeep Simha May 04 '14 at 13:21
  • Read [Eclipse : how we take arguments for main when run](http://stackoverflow.com/questions/12222153/eclipse-how-we-take-arguments-for-main-when-run) – PakkuDon May 04 '14 at 13:23
  • For any "real" Java application (not a testcase or toy) you should check args.length before you access individual args values. – Hot Licks May 04 '14 at 13:58
  • 1
    possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Braiam Oct 20 '14 at 09:24

2 Answers2

15

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 (2, because you're accessing args[0] and args[1])

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

Joffrey
  • 32,348
  • 6
  • 68
  • 100
3

This code expects to get two arguments when it's run (the args array). The fact that accessing args[0] causes a java.lang.ArrayIndexOutOfBoundsException means you aren't passing any.

Mureinik
  • 297,002
  • 52
  • 306
  • 350