Download presentation
Presentation is loading. Please wait.
Published byBrent Austin Modified over 9 years ago
1
The Fine Points of Conditionals
2
When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return true if the party with the given values is successful, or false otherwise. cigarParty(30, false) → false cigarParty(50, false) → true cigarParty(70, true) → true
3
There is no magic way to say “between” public boolean cigarParty(int cigars, boolean isWeekend) { want 40<= cigars <= 60. In Java: if(40 <= cigars && cigars <= 60)
4
When you “return”, the method ends public boolean cigarParty(int cigars, boolean isWeekend) { if (isWeekend){ if (40 <= cigars){ return true; } else{ if(40 <= cigars && cigars <= 60){ return true; } return false; } I know it’s false now. If it were true I’d have returned by now…
5
When you “return”, the method ends public boolean cigarParty(int cigars, boolean isWeekend) { if (isWeekend){ if (40 <= cigars){ return true; } else{ if(40 <= cigars && cigars <= 60){ return true; } return false; System.out.println(“Done”); } Error: Unreachable code
6
There doesn’t have to be an else public boolean cigarParty(int cigars, boolean isWeekend) { if (isWeekend && 40 <= cigars){ return true; } if(!isWeekend && 40 <= cigars && cigars <= 60){ return true; } return false; }
7
Not all returns can be in ifs public boolean cigarParty(int cigars, boolean isWeekend) { if (isWeekend && 40 <= cigars){ return true; } if(!isWeekend && 40 <= cigars && cigars <= 60){ return true; } if (isWeekend && 40 > cigars){ return false; } if (!isWeekend && (cigars 60)){ return false; }
8
Variable Scope public boolean cigarParty(int cigars, boolean isWeekend) { if (cigars < 40){ boolean enough = true; } if (!isWeekend && cigars >= 40 && cigars <= 60){ enough = true; } Java doesn’t know this variable!
9
One-liners When you write an if or else clause that is only one line long, you don’t need the { }. Be careful with this shortcut!
10
public boolean cigarParty(int cigars, boolean isWeekend) { if(cigars < 40) return false; if (isWeekend) return true; if(cigars <= 60) return true; return false; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.