You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java表达式求解程序处理除法时触发IndexOutOfBoundsException求助

IndexOutOfBoundsException when handling division in Java expression solver

Hey folks, I'm working on an expression solver program in Java that handles addition, subtraction, and multiplication just fine, but whenever it tries to process the division operator /, it throws an index out of bounds exception. I'm stumped on how to debug this and would appreciate some troubleshooting guidance (please don't give the direct fix—I want to work through it myself to learn!).

Thanks in advance!

My main program class:

import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Integer.*;
import static java.lang.System.*;

public class ExpressionSolver {
    int answer;
    String expString;
    ArrayList<String> exp;

    public ExpressionSolver(String s) {
        setExpression(s);
    }

    public void setExpression(String s) {
        expString = s;
        exp = new ArrayList<String>();
        for(String temp: s.split(" ")) {
            exp.add(temp);
        }
    }

    public void solveExpression() {
        int index1, index2, num1, num2;
        while(exp.contains("*") || exp.contains("/")) {
            index1 = exp.indexOf("*");
            index2 = 0;
            if(index1 <= 0) {
                index1 = exp.indexOf("/");
                index2 = 1;
            }
            num1 = Integer.parseInt(exp.get(index1-1));
            num2 = Integer.parseInt(exp.get(index1+1));
            if(index2 == 0) {
                answer = num1 * num2;
            } else {
                answer = num1 / num2;
            }
            exp.remove(index1 - 1);
            exp.remove(index1 - 1);
            exp.set(index1 - 1, Integer.toString(answer));
        }
        while(exp.contains("+") || exp.contains("-")) {
            index1 = exp.indexOf("+");
            index2 = 0;
            if(index1 <= 0) {
                index1 = exp.indexOf("-");
                index2 = 1;
            }
            num1 = Integer.parseInt(exp.get(index1-1));
            num2 = Integer.parseInt(exp.get(index1+1));
            if(index2 == 0) {
                answer = num1 + num2;
            } else {
                answer = num1 - num2;
            }
            exp.remove(index1 - 1);
            exp.remove(index1 - 1);
            exp.set(index1 - 1, Integer.toString(answer));
        }
    }

    public String toString() {
        return expString + " = " + answer;
    }
}

My runner class:

import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.Integer.*;
import static java.lang.System.*;

public class ExpressionSolverRunner {
    public static void main( String args[] ) {
        ExpressionSolver test = new ExpressionSolver("3 + 3");
        test.solveExpression();
        System.out.println(test);

        test.setExpression("3 * 5");
        test.solveExpression();
        System.out.println(test);

        test.setExpression("3 - 5");
        test.solveExpression();
        System.out.println(test);

        test.setExpression("3 / 5");
        test.solveExpression();
        System.out.println(test);
    }
}

Program output:

----jGRASP exec: java ExpressionSolverRunner
3 + 3 = 6
3 * 5 = 15
3 - 5 = -2
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 99, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.set(ArrayList.java:444)
    at ExpressionSolver.solveExpression(ExpressionSolver.java:60)
    at ExpressionSolverRunner.main(ExpressionSolverRunner.java:29)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

Whenever the program processes 3 / 5, it hits the out-of-bounds error. The expected result should be 0.

Troubleshooting Guidance

Here are some steps to help you track down the issue:

  • Start by examining the logic that selects which operator to process first in the multiplication/division loop. What does exp.indexOf("*") return when there's no multiplication operator present? Does this lead your condition index1 <= 0 to behave in a way you didn't intend?
  • Manually trace through the steps of the division operation. After you remove two elements from the exp ArrayList, how does the list's size change? Remember that removing elements shifts the indices of remaining elements, which can break subsequent get or set calls if you're not accounting for this shift.
  • Add debug prints to check the state of the exp list and the value of index1 right before the line that throws the exception. For example, printing exp.size() and index1 can show you exactly why the index is out of bounds relative to the current list size.
  • Consider the loop condition for the multiplication/division loop. When the only operator left is /, does the loop terminate correctly after processing it, or does it attempt to run again, leading to trying to access elements that no longer exist?

内容的提问来源于stack exchange,提问作者NightCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:16:20