RAAAAM
RAAAAM

Reputation: 3380

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 to 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.

Upvotes: 2

Views: 26726

Answers (4)

Jason Rogers
Jason Rogers

Reputation: 19344

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.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881293

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
}

Upvotes: 3

Reno
Reno

Reputation: 33792

Use a

break;

inside your loop.

Upvotes: 2

Corey Sunwold
Corey Sunwold

Reputation: 10254

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

Upvotes: 1

Related Questions