得到一个数组的索引为patrticular值 [英] get the index of an array for a patrticular value

查看:189
本文介绍了得到一个数组的索引为patrticular值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayIndex |价值|运行总计
-------------------------------
   0 | 6 | 6
   1 | 1 | 7
   2 | 6 | 13
   3 | 2 | 15
我:数组索引
五:价值
R:运行总计

我需要选择给定运行总计合适的索引,例如 12是给定的运行总计,因此相应的指数是2,我会把我的code座波纹管它不工作我已经用断尝试; if语句以及后,任何人都可以帮我解决这个问题,请:)

  INT running_total = 0;
布尔V = FALSE;
    为(中间体X = 0 X  - 其中= array.length; X ++)
        {
        running_total + =阵列[X]
        如果(running_total> = 12)
            {
            如果(V = FALSE)
                {
                V =真实;
                othermethods(X);
                }
            }
        }
 

解决方案

在你的方法,唯一的错误是你让 X 运行阵列.length 包容性,导致飞机坠毁与 ArrayIndexOutOfBoundsException异常当总小于12。

更改code到

 的for(int x = 0,X< array.length; X ++){
    ...
}
 

,以避免崩溃。

另一个点式是不是写 v ==假更传统的写!v 。最后,因为其目的是阻止呼叫 othermethods(X)发现那里的运行总计满足的情况下,你可以重写与循环中的第一个索引后,<$ C $而不是一个布尔变量C>破发:

 的for(int x = 0,X&LT; array.length; X ++){
    running_total + =阵列[X]
    如果(running_total&GT; = 12){
        othermethods(X);
        打破;
    }
}
 

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);
                }
            }
        }

解决方案

The only error in your method is that you let x run to array.length inclusive, causing a crash with ArrayIndexOutofBoundsException when the total is less than 12.

Change your code to

for(int x=0 ; x < array.length ; x++) {
    ...
}

to avoid the crash.

Another "point for style" is that instead of writing v==false it is more conventional to write !v. Finally, since the intent is to stop calling othermethods(x) after finding the first index where the running total satisfies the condition, you can rewrite the loop with a break instead of a boolean variable:

for(int x=0 ; x < array.length ; x++) {
    running_total+=array[x];
    if(running_total >= 12) {
        othermethods(x);
        break;
    }
}

这篇关于得到一个数组的索引为patrticular值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆