运行时错误(ArrayOutOfBoundException)

时间:2014-06-18 18:50:40

标签: 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]);       
       c = Integer.parseInt(args[2]);       
       sum = a+b+c;         
       System.out.println("Command Line Sum is "+sum);          
     }     
 } 

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

4 个答案:

答案 0 :(得分:2)

当您尝试引用数组中不存在的索引时,会出现ArrayIndexOutOfBoundsException。在这里,你隐含地假设你给程序三个参数(或更多)。如果它在没有参数的情况下运行,args[0]将生成此异常。如果它使用一个参数运行,您将在args[1]上获得例外,并且如果它使用两个参数运行,args[2]将导致所述异常。

答案 1 :(得分:1)

正如上面的回答所述,您遇到的异常是因为您正在尝试访问超出数组最大长度的数组元素。

有几种方法可以解决这个问题。首先,如果你想确保总是有3个参数发送到你的程序,你可以抛出一个例外:

    if (args.length < 3) {
        throw new Exception("This program requires 3 arguments");
    }

另一方面,如果您只想总结发送到程序的所有参数,而不关心发送给它的参数数量,可以使用foreach循环(参见文档和更多示例) HERE)。这可以这样实现:

    int sum = 0;
    for(String intString : args){
        sum += Integer.parseInt(intString);
    }

如果您正在寻找关于为什么会发生这种情况的更多解释,那么它与如何在内存中处理数组有关。当一个数组在内存中初始化时,它被赋予一个特定的字节数,其中被分配为该数组的内存。在这些字节之外,是与当时发生的任何其他事件相对应的内存值和位置,与您的阵列无关。把它想象成一个带围栏的院子,当你试图进入阵列内部的某些东西时,你就在围栏内,一切顺利。但是,当你试图访问阵列之外的东西时,你正试图越过围栏进入你不属于的地方。

这种情况最有可能发生,因为3个值未作为参数传递到您的程序中。所以你的围栏可能只有1平方英尺,你试图越过围栏到第3平方英尺,这个区域不是你的。

答案 2 :(得分:0)

你需要使用所有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);
}

}

答案 3 :(得分:0)

运行时需要为其提供参数。 如果要从命令行运行它,则必须键入例如&#34; java Command 5 2 6&#34;。然后,&#34; 5&#34;将是args [0],&#34; 2&#34;将是args [1]和&#34; 6&#34;将是args [2]。 如果您使用Eclipse,则可以在Run-&gt; Run Configurations下应用这些参数。在出现的窗口中,单击选项卡&#34; Arguments&#34;并在TextArea中输入它们,标记为&#34;程序参数&#34;。 然后,只需单击&#34;应用&#34;,然后像以前一样运行它。

相关问题