Java 错误“线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15648066/
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-10-31 20:24:48  来源:igfitidea点击:

Java Error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException"

java

提问by Asim Qureshi

Here is this simple code from my book it produces error message in netbeans and in compile version (.class) version running through Command prompt.

这是我书中的这个简单代码,它在通过命令提示符运行的 netbeans 和编译版本 (.class) 版本中产生错误消息。

Error Message

错误信息

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at intocm.Intocm.main(Intocm.java:17)

Simple Program to convert inches to centimeter.

将英寸转换为厘米的简单程序。

package intocm;

public class Intocm {

    public static void main(String[] args) {
        // TODO code application logic here
        double inches;
        inches = Double.valueOf(args[0]).doubleValue();
        double cm;
        cm = inches * 2.54;
        System.out.println(cm + "Centimeters");
    }
}

The Line which Causes error is

导致错误的行是

inches = Double.valueOf(args[0]).doubleValue();

I don't know why this array "args" causing this error please help me in understanding this.

我不知道为什么这个数组“args”会导致这个错误,请帮助我理解这一点。

Thank you.

谢谢你。

回答by PermGenError

You are not passing command line arguments. args[0]is expecting a command line argument.

您没有传递命令行参数。args[0]期待命令行参数。

IF you are running it from command line try this:

如果您从命令行运行它,请尝试以下操作:

java Intocm 12.0

In eclipse

在日食

Run---> Run Configuration--->
                            Arguments Tab--->
                                            give program arguments-->
                                                                  apply---> run

回答by Ron Dahlgren

The argsparameter in a class's mainmethod is supplied by command line arguments. You are not invoking the jar with any command line args, so the array has no zero element.

argsmain方法中的参数由命令行参数提供。您没有使用任何命令行参数调用 jar,因此该数组没有零元素。

回答by rgettman

If args[0]is causing an ArrayIndexOutOfBoundsException, then you didn't supply any command-line parameters. Test args.length; if it's 0, then handle the error.

如果args[0]导致ArrayIndexOutOfBoundsException,那么您没有提供任何命令行参数。测试args.length;如果是0,则处理错误。