java.lang.ArrayIndexOutOfBoundsException:0

问题描述 投票:5回答:2

我正在使用一本书学习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);

}
java arrays exception indexoutofboundsexception
2个回答
9
投票

问题

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

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

可能的解决方案

  • 如果从命令行运行程序,请不要忘记在命令中传递2个参数。
  • 如果您在Eclipse中运行程序,则应在运行配置中设置命令行参数。转到Run > Run configurations...,然后为运行配置选择Arguments选项卡,并在程序参数区域中添加一些参数。

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

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

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


2
投票

这段代码在运行时需要得到两个参数(args数组)。访问args[0]导致java.lang.ArrayIndexOutOfBoundsException的事实意味着你没有通过任何。

© www.soinside.com 2019 - 2024. All rights reserved.