简体   繁体   中英

How do you write multiple conditions on if statements

if (num1 == (1,2,3,4,5,6,7,8,9)){
      *some command*
}

does this sequence work, if not can you guide me masters. I'm a beginner

Try this:

if(num1 >= 1 && num1 <= 9) {
// Some code
}

&& operator will make sure num1 should be between 1 to 9 including it (ie 1, 9). It will execute some code only if both the conditions are true .

If the numbers you're testing for are in a continuous range, you can bound the value with greater than and less than (or equals):

For example, if you're testing if an int n is one of 1, 2, 3, 4, 5, 6, 7, 8, 9, you can do this:

if(n >= 1 && n <= 9)
{
    // Code
}

If, however, the numbers are not a continuous range you have no choice but to explicitly test every value. So, if you were checking if n was one of 13, 57, -3, 11, -66, 100, you could have to write it out completely (or use a switch statement or lookup table):

if(13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n)
{
    // Code
}

Alternatively (only for integral types):

switch (n)
{
    case 13:
    case 57:
    case -3:
    case 11:
    case -66:
    case 100:
        // Code
        break;
 }

You may want to write a helper method in the latter case to make it more clear what you're testing for. eg:

if(IsAcceptableValueForTask(n))

Where IsAcceptableValueForTask returns an int representing the truth ( 1 | 0 ) of 13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n 13 == n || 57 == n || -3 == n || 11 == n || -66 == n || 100 == n

You can use

if (num1 == 1 || num1 == 2 || num1 == 3 || num1 == 4 || num1 == 5 || num1 == 6 || num1 == 7 || num1 == 8 || num1 == 9 ){
      //code
}

If you want to check between a range of numbers you can use

if(num1 >= 1 && num1 <= 9) {
    //code
}

You can also use switch statement for more convenience if the numbers are random and there are many conditions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM