开发者

How to compare Integer with integer array

i am new to android. I want to know how to compare Integer with integer array. There is a set of integer array (Ex) array_int={1,2,3,4} and single integer int i=2, here i want 开发者_如何学JAVAto compare both integers,and in case if single integer appears in array integer, i want to break the process.

for(i=0;i<integerArray.length;i++){
    if(singleinteger!=integerArray[i]){ // some action       }
else{
// Stop the action  }

In this case it compares both integer. and at the time when two integers are equal process getting break, otherwise it iteration action till the loop getting end.


For a simple solution, use:

for (i = 0; i < intArray.length; i++) {
    if (singleInt != intArray[i]) {
        // some action
    } else {
        break;
    }
}

That will break from the loop when the two values are equal. However, some purists don't like the use of break since it can introduce readability issues, especially if your some action is large (in terms of lines of code) since that removes an exit condition far away from the for itself.

To fix that, you may want to consider reversing the sense of the if statement so that that exit condition is closer to the for:

for (i = 0; i < intArray.length; i++) {
    if (singleInt == intArray[i])
        break;

    // some action
}

and that will also let you remove the else (that's the else itself, not its contents) since it's not needed any more.

But, if you're going to do that, you may as well incorporate it totally into the for and be done with it:

for (i = 0; (i < intArray.length) && (singleInt != intArray[i]); i++) {
    // some action
}


Use a

break;

inside your loop.


for(i = 0; i < integerArray.length; i++ {
    if(singleinteger != integerArray[i] { 
        //some action
    }
    else { 
        break; //add this line
    }
}


If you want you can read up on Integer test here

Otherwise in your code your simply missing the "exit" of your loop.

    for(i=0;i<integerArray.length;i++){
        if(singleinteger!=integerArray[i]){ // some action
    }else{
    // Stop the action  
       break;
    }

but that is only if you don't need to process the rest of your array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜