asdasdasdasdqwe
asdasdasdasdqwe

Reputation: 331

which condition is true in an if statement

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?

Upvotes: 0

Views: 3584

Answers (7)

paxdiablo
paxdiablo

Reputation: 881223

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

Upvotes: 3

Panshul
Panshul

Reputation: 956

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

Upvotes: 0

IsisCode
IsisCode

Reputation: 2490

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.

Upvotes: 1

cli_hlt
cli_hlt

Reputation: 7164

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.

Upvotes: 1

mortdeus
mortdeus

Reputation: 197

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.

Upvotes: -1

David Harris
David Harris

Reputation: 2340

No. You'll have to do something like:

if(condition1 || condition2 || condition3)

{

if (condition1) {
}

if (condition2) {
}

if (condition3) {
}

//do something

}

Upvotes: 1

Bartvbl
Bartvbl

Reputation: 2928

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.

Upvotes: 0

Related Questions