How to compare Integer with integer array

前端 未结 4 983
你的背包
你的背包 2021-01-07 04:47

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 wa

相关标签:
4条回答
  • 2021-01-07 04:54

    Use a

    break;
    

    inside your loop.

    0 讨论(0)
  • 2021-01-07 04:55
    for(i = 0; i < integerArray.length; i++ {
        if(singleinteger != integerArray[i] { 
            //some action
        }
        else { 
            break; //add this line
        }
    }
    
    0 讨论(0)
  • 2021-01-07 05:03

    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 讨论(0)
  • 2021-01-07 05:15

    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
    }
    
    0 讨论(0)
提交回复
热议问题