java.lang.ArrayIndexOutOfBoundsException:0

pg2*_*014 5 java arrays exception indexoutofboundsexception

我正在使用一本书学习java.有这个练习,我无法正常工作.它使用java类Double添加了两个双精度数.当我尝试在Eclipse中运行此代码时,它会在标题中给出错误.

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

}
Run Code Online (Sandbox Code Playgroud)

Jof*_*rey 10

问题

ArrayIndexOutOfBoundsException: 0意味着索引0不是数组的有效索引args[],这反过来意味着您的数组为空.

在方法的这种特殊情况下main(),这意味着没有参数在命令行上传递给您的程序.

可能的解决方案

  • 如果从命令行运行程序,请不要忘记在命令中传递2个参数.

  • 如果您在Eclipse中运行程序,则应在运行配置中设置命令行参数.转到Run > Run configurations...然后选择Arguments运行配置的选项卡,并在程序参数区域中添加一些参数.

请注意,您应该处理没有给出足够参数的情况,在main方法的开头有类似的内容:

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

这将优雅地失败,而不是让您的程序崩溃.