which condition is true in an if statement

独自空忆成欢 提交于 2019-12-02 21:59:39

问题


say I have an if statement as such

if(condition1 || condition2 || condition3)
{
 //do something
}

Is it possible to find out which of the 3 conditions was true when we enter the loop?


回答1:


Yes, you can check each one individually with something like:

if(condition1 || condition2 || condition3) {
    if (condition1) { doSomethingOne(); }
    if (condition2) { doSomethingTwo(); }
    if (condition3) { doSomethingThree(); }
    doSomethingCommon();
}

assuming of course that the conditions aren't likely to change in the interim (such as with threading, interrupts or memory-mapped I/O, for example).




回答2:


No. You'll have to do something like:

if(condition1 || condition2 || condition3)

{

if (condition1) {
}

if (condition2) {
}

if (condition3) {
}

//do something

}




回答3:


It is possible to find out which of the conditions was true by querying each of them using another if, effectively rendering the first if useless.




回答4:


A simple method.

if(condition1 || condition2 || condition3)
    {
     if(condition1){
      //do something
     }
     if(condition2){
      //do something
     }
     if(condition3){
      //do something
     }
}

Or if you know that only one of the conditions is going to be true, consider using a switch.




回答5:


Before you call the if statement, you can call:

System.out.println(condition1);
System.out.println(condition2);
System.out.println(condition3);

to find out which of the conditions was true. If you would like to make the program behave differently according to the condition you will need to put that code in a separate if statement.




回答6:


No. However you can achieve by: i. Using seperate if else within the 3 or conditions or ii. break the three or conditions in separate pairs to find out matching value




回答7:


You have the short circuit operators. || and &&.

So say for instance you have the condition,

if( x && y || z)

If x && y doesnt evaluate to true, then y and z are never compared. However if X and Y are true, then it will test y or z. In this case your true value comes from the fact that x and y is true, and y or z is true.



来源:https://stackoverflow.com/questions/9102687/which-condition-is-true-in-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!