java - 获取特定值的数组索引

标签 java arrays algorithm search

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/

相关文章:

java - Android 应用程序中 key 的反黑客解决方案?

java - Spring注解码件

来自本地存储的javascript 'object object'

algorithm - 主成分初始化如何确定自组织映射中映射向量的权重?

algorithm - 如何在线性时间内找到从 DAG 中的节点可到达的最小值?

Java完美数嵌套for循环

java - PatternSyntaxException 可能有多种原因吗?

c - 二维数组中穿过障碍物(地雷)的最短路径(C 编程)

Javascript:我的数组的大小随着每次 for 循环迭代而减小。为什么?

c++ - 在 C++ CT 重建算法中使用数组