Java 运行时错误(ArrayOutOfBoundException)

Java 运行时错误(ArrayOutOfBoundException),java,Java,获取运行时错误ArrayOutOfBoundException class Command { public static void main(String[] args) { int a,b,c,sum; a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]);

获取运行时错误
ArrayOutOfBoundException

class Command
{   
    public static void main(String[] args)  
    {       
       int a,b,c,sum;                       
       a = Integer.parseInt(args[0]);       
       b = Integer.parseInt(args[1]);       
       c = Integer.parseInt(args[2]);       
       sum = a+b+c;         
       System.out.println("Command Line Sum is "+sum);          
     }     
 } 

//此代码中的错误是什么?

您需要使用所有3个参数进行调用,否则将获得arrayindexoutofboundsexception

class Command {
public static void main(String[] args) throws Exception {


    if(args.length != 3){
        throw new Exception("You must set all three arguments, a,b,c");
    }

    if(null == args[0]){
        throw new Exception("a not supplied");
    }

    if(null == args[1]){
        throw new Exception("b not supplied");
    }

    if(null == args[2]){
        throw new Exception("c not supplied");
    }

    int a, b, c, sum;
    a = Integer.parseInt(args[0]);
    b = Integer.parseInt(args[1]);
    c = Integer.parseInt(args[2]);
    sum = a + b + c;
    System.out.println("Command Line Sum is " + sum);
}

}当您尝试引用数组中不存在的索引时,会发生
数组索引OutofBounds异常。这里,您隐式地假设您为程序提供了三个(或更多)参数。如果运行时没有参数,
args[0]
将生成此异常。如果使用一个参数运行,您将在
args[1]
上获得异常,如果使用两个参数运行,
args[2]
将导致所述异常。

如上所述,您遇到的异常是,您试图访问的数组元素超过了数组的最大长度

有两种方法可以处理这个问题。首先,如果要确保始终有3个参数发送到程序,可以抛出如下异常:

    if (args.length < 3) {
        throw new Exception("This program requires 3 arguments");
    }
如果您想了解更多关于为什么会发生这种情况的解释,那么它与内存中如何处理数组有关。当一个数组在内存中初始化时,它会被指定一个特定的字节数,在这个字节数中,数组被分配为内存。在这些字节之外,是内存值和位置,它们可以对应于当时发生的任何其他事件,而与数组无关。把它想象成一个被栅栏围起来的院子,当你试图接近阵列内部的东西时,你就在栅栏内,一切都很顺利。但是,当您试图访问阵列之外的内容时,您正试图越过围栏进入一个不属于您的地方


这很可能是因为3个值没有作为参数传递到程序中。因此,您的围栏可能只包含1平方英尺,而您正试图越过围栏到达第三平方英尺,这不是您的区域。

您输入了什么指令来运行代码?在将其发布到此处之前,您是否阅读了此异常?是否有
字符串[]args
的值?如果不是,那么您正试图解析不存在的信息。
    int sum = 0;
    for(String intString : args){
        sum += Integer.parseInt(intString);
    }