1

My while loop looks like this currently:

    while((0 <= trader.getWallet()) || (0 <= days)) {  
// do something
}

so if any of those two conditions are false somewhere in the loop the program will exit, but my program doesn't seem to listen to the second condition only the first, but it would listen to them separately if I just put them in one at a time for testing, so did I write this while loop wrong?

5
  • 1
    any of those two conditions can be false at the start of that loop, since it's a logical OR, not a logical AND you are using Commented May 19, 2021 at 6:37
  • 3
    Are you sure you meant "less than" in both of those conditions? Read the whole thing out loud and make sure it makes sense. Commented May 19, 2021 at 6:52
  • @chrylis-cautiouslyoptimistic- Good methodology for debugging boolean expression Commented May 19, 2021 at 7:01
  • Note that most people would write days >= 0 instead of 0 <= days. Commented May 19, 2021 at 8:02
  • it's being short-circuited most likely. Commented May 19, 2021 at 9:12

2 Answers 2

3

In case of Logical OR if any one of the two conditions is true whole statement shall execute to be true. In case of Logical AND both the conditions have to be true for the whole statement to be true. So ,you can use logical AND

while((trader.getWallet>=0()) && (days>=0))
Sign up to request clarification or add additional context in comments.

Comments

1

If the first condition is true then OR won't evaluate the second condition,

Instead, it should be

while(trader.getWallet() > 0 && days > 0) {  
   // do something
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.