java.lang.ArrayIndexOutOfBoundsException: 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23456742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:06:48  来源:igfitidea点击:

java.lang.ArrayIndexOutOfBoundsException: 0

javaarraysexceptionindexoutofboundsexception

提问by pg2014

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.

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

}

采纳答案by Joffrey

Problem

问题

This ArrayIndexOutOfBoundsException: 0means that the index 0is not a valid index for your array args[], which in turn means that your array is empty.

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

In this particular case of a main()method, it means that no argument was passedon to your program on the command line.

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

Possible solutions

可能的解决方案

  • If you're running your program from the command line, don't forget to pass 2 arguments in the command.

  • 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 Argumentstab for your run configuration and add some arguments in the program argumentsarea.

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

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

Note that you should handle the case where not enough arguments are given, with something like this at the beginning of your main method:

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

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

This would fail gracefully instead of making your program crash.

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

回答by Mureinik

This code expects to get two arguments when it's run (the argsarray). The fact that accessing args[0]causes a java.lang.ArrayIndexOutOfBoundsExceptionmeans you aren't passing any.

此代码期望在运行时获得两个参数(args数组)。访问args[0]导致 a的事实java.lang.ArrayIndexOutOfBoundsException意味着您没有通过任何。