这个Java程序做了一个简单的计算,它应该输出123+1
的数值
(The output should be 124.) (Ignore the last "+" string.)
我在 if 语句中遇到错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
我对 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);
最佳答案
while(i<=(math.length()-1))
数学长度为 6,在侧循环中,数组长度为 4
你可能想写
while(i<=(arrayz.length-1))
关于java - 数组索引越界帮助 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20811593/