java.lang.ArrayIndexOutOfBoundsException:0
我正在用书来学习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); }
问题
这个ArrayIndexOutOfBoundsException: 0意味着索引0不是你的数组args[]的有效索引,这又意味着你的数组是空的。
在main()方法的这种特殊情况下,这意味着在命令行上没有parameter passing给你的程序。
可能的解决scheme
-
如果从命令行运行程序,请不要忘记在命令中传递2个参数。
-
如果您在Eclipse中运行程序,则应该在运行configuration中设置命令行参数。 转到
Run > Run configurations...,然后为运行configurationselect“Arguments选项卡,并在程序参数区域中添加一些参数。
请注意, 您应该处理没有给出足够参数的情况,在main方法的开始处使用类似的方法:
if (args.length < 2) { System.err.println("Not enough arguments received."); return; }
这会失败,而不是让你的程序崩溃。
这个代码在运行时期望得到两个参数( args数组)。 访问args[0]导致java.lang.ArrayIndexOutOfBoundsException意味着你没有传递任何信息。