Multiple Conditions
Combine conditions with && (and) and || (or), and use parentheses to group them so the if means what you intend.
Apprentice · Java · Updated
Sometimes, you need to make decisions based on multiple factors. For example, maybe you only eat at Riverside Steakhouse on the weekend, but you still have to have enough money.
And / Or Operators
| Operator | Meaning |
|---|---|
&& |
Logical AND: both conditions must be true |
\|\| |
Logical OR: at least one condition must be true |
( ) |
Put parentheses around two OR conditions so the AND applies to both of them together |
int availableCash = 100;
String dayOfTheWeek = "Wednesday";
if(
availableCash > 50 &&
(dayOfTheWeek.equals("Saturday") || dayOfTheWeek.equals("Sunday"))
)
{
System.out.println("You can eat at Riverside Steakhouse");
}
else if(availableCash > 20)
{
System.out.println("You can eat at Slice Palace Pizza");
}
else
{
System.out.println("You can eat at Burger Barn");
}
Do it: decide whether you can go to brunch
The diner down the street serves brunch only on Saturday and Sunday, and brunch costs $25. Write a function that says whether you can go.
The function gets two values:
availableCash: how many dollars you have, anint(30).dayOfTheWeek: the day's name, aStringwith a capital first letter ("Sunday").
You can go when both rules are true. For example, with $30 on Sunday:
| Rule | With $30 on "Sunday" |
|---|---|
| You have $25 or more | Yes: 30 is more than 25 |
The day is "Saturday" or "Sunday" |
Yes: it's "Sunday" |
Both are true, so canGetBrunch(30, "Sunday") returns true.
Your job: write the function boolean canGetBrunch(int availableCash, String dayOfTheWeek).
- Return
truewhen you have $25 or more and the day is"Saturday"or"Sunday". - Return
falseotherwise: not enough cash, a weekday, or both. - Exactly $25 is enough.
- The day is always written with a capital first letter, as in
"Saturday".
Practiced live on the lesson page: write the Java right there and check it.