Вопрос

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

}
Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top