该Java程序进行了简单的计算,并且假定输出123+1的数值



我在if语句中遇到错误:



我做了arrayz[i-1]arrayz[i+1]的打印输出,似乎可以接受地分别打印123和1,这是正确的。所以,我不确定这是怎么回事。

        String math = "123+1+";
        String arrayz[]={"123","+","1","+"};
        double total =0.0;

        int i=0;
        while(i<=(math.length()-1))        //don't bother with the last char
        {       i++;
            if(arrayz[i].equals("+"))
            {
                total = Double.parseDouble((String)arrayz[i-1]) + Double.parseDouble((String)arrayz[i+1]);

            }

        }

        System.out.println(total);

最佳答案

由于您将i与数组arrayz一起使用,因此必须使用arrayz.length而不是math.length()
编辑

这应该工作:

public static void main(String[] args)
{
    String math = "123+1+";
    String arrayz[] = { "123", "+", "1", "+" };
    double total = 0.0;

    int i = 0;

    // arrayz.length - 2 -> because you are accessing "arrayz[i + 1]",
    // arrayz.length - 1 would be OK if the maximum index you were using were "arrayz[i] "
    while (i <= (arrayz.length - 2)) //don't bother with the last char
    {
        if (arrayz[i].equals("+")) {
            total = Double.parseDouble((String) arrayz[i - 1]) + Double.parseDouble((String) arrayz[i + 1]);
        }
        i++; // Increment at the end of the loop
    }

    System.out.println(total);
}

10-07 13:11