线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:索引1超出长度1的范围

时间:2020-09-30 03:14:27

标签: java

我是编程新手,下面的代码无法编译,不知道为什么会这样。该程序应该采用多个命令行参数,将其解析为双精度,然后将其添加到currentBalance中。但是,如果有一个字符串命令(例如,“ sub”用于减法),则应采用该字符串,并计算前后的双精度数,然后将其添加到当前的Balance中。任何帮助将不胜感激,谢谢。

public static void main(String[] args) throws InterruptedException{
    // ends program if no input given
    if(args.length == 0){
        return;
    }
    // starting balance
    double currentBalance = 500;
    int location = args.length; //stores count of CLIs into location 
    int penaltyFlag = 0;
    double op1 = 0;
    double op2 = 0;
    String operator = "";
    

    
    //Test to make sure that inputs can be parsed, would throw exception if can't parse anything
     for(int i = 0; i < location ; i++){
                    // test to see if next arg is double or operator
                    // if next arg is an operator then take arg and do operation 
                    if(isValidDouble(args[i]) && isValidOperator(args[i+1])){ 
                        //input must be a valid operator to continue here
                        operator = args[i];
                        op1 = Double.parseDouble(args[i-1]);
                        op2 = Double.parseDouble(args[i+2]);
                        currentBalance += operation(op1, op2, operator);
                        System.out.println("Your balance: $" + currentBalance);     
                    } 
                    // if next operator is a double, add this arg and continue
                    else if(isValidDouble(args[i])){
                        double singleOperand = Double.parseDouble(args[i]);
                        currentBalance += singleOperand;
                        System.out.println("Your balance: $" + currentBalance);
                    } }

2 个答案:

答案 0 :(得分:0)

在“ op2 = Double.parseDouble(args [i + 2]);”中,“ i + 2”将大于args.length并导致出站异常

答案 1 :(得分:0)

我非常确定您会收到此错误,因为您访问的是args之外的值,它们不在args的范围内。我的意思是在for循环中,您正在从i = 0循环到i < location。但是,在此for循环中,您正在调用args[i-1]args[i+2]args[i+1]

这意味着,当i为0(刚刚开始for循环)时,您正在向args询问args[0-1] = args[-1]处的值,该值无效。关于args[i+2]args[i+1],当for循环结束并且i = location - 1i < location的最后一个值)结束时,您正在调用args[(location - 1) + 1]和{{1} },两者都将得出args[(location - 1) +2]中不存在的索引,因为您将args定义为args的长度。这是描述我的意思的图片:

enter image description here