java.lang.ArrayIndexOutOfBoundsException: 0 [英] java.lang.ArrayIndexOutOfBoundsException: 0
问题描述
我正在用一本书学习 Java.有一个我无法正常工作的练习.它使用 java 类 Double 添加两个双精度值.当我尝试在 Eclipse 中运行此代码时,它给了我标题中的错误.
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);
}
推荐答案
问题
这个 ArrayIndexOutOfBoundsException: 0
意味着索引 0
不是数组 args[]
的有效索引,这反过来意味着你的数组是空的.
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.
在 main()
方法的这种特殊情况下,这意味着没有参数被传递到命令行上的程序.
In this particular case of a main()
method, it means that no argument was passed on to your program on the command line.
如果您从命令行运行程序,请不要忘记在命令中传递 2 个参数.
If you're running your program from the command line, don't forget to pass 2 arguments in the command.
如果您在 Eclipse 中运行您的程序,您应该在运行配置中设置命令行参数.转到<代码>运行>运行配置...,然后为您的运行配置选择Arguments
选项卡,并在程序参数 区域中添加一些参数.
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.
请注意,您应该处理没有提供足够参数的情况,在 main 方法的开头使用类似这样的内容:
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.
这篇关于java.lang.ArrayIndexOutOfBoundsException: 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!