ArrayIndex|Value|Running total ------------------------------- 0 | 6 | 6 1 | 1 | 7 2 | 6 | 13 3 | 2 | 15 I:array index V:value R:Running total
I need to select the appropriate index for the given running total , for example 12 is the given running total ,so the appropriate index is 2, i will put my code block bellow its not working i have tried using break; after the if statement as well , anyone one can help me solve this please:)
int running_total = 0;
boolean v=false;
for(int x=0;x<=array.length;x++)
{
running_total+=array[x];
if(running_total>=12)
{
if(v==false)
{
v= true;
othermethods(x);
}
}
}
最佳答案
你的方法中唯一的错误是你让 x
运行到 array.length
包括在内,导致崩溃并出现 ArrayIndexOutofBoundsException
当总小于 12。
将您的代码更改为
for(int x=0 ; x < array.length ; x++) {
...
}
避免崩溃。
另一个“风格要点”是,与其编写 v==false
,不如编写 !v
更为传统。最后,由于目的是在找到运行总计满足条件的第一个索引后停止调用 othermethods(x)
,因此您可以使用 break
重写循环,而不是一个 boolean 变量:
for(int x=0 ; x < array.length ; x++) {
running_total+=array[x];
if(running_total >= 12) {
othermethods(x);
break;
}
}
关于java - 获取特定值的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445605/