E N D
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) → falsecigarParty(50, false) → truecigarParty(70, true) → true
There is no magic way to say “between” public booleancigarParty(int cigars, booleanisWeekend) { want 40<= cigars <= 60. In Java: if(40 <= cigars && cigars <= 60)
When you “return”, the method ends public booleancigarParty(int cigars, booleanisWeekend) { 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…
When you “return”, the method ends public booleancigarParty(int cigars, booleanisWeekend) { if (isWeekend){ if (40 <= cigars){ return true; } } else{ if(40 <= cigars && cigars <= 60){ return true; } } return false; System.out.println(“Done”); } Error: Unreachable code
There doesn’t have to be an else public booleancigarParty(int cigars, booleanisWeekend) { if (isWeekend&& 40 <= cigars){ return true; } if(!isWeekend && 40 <= cigars && cigars <= 60){ return true; } return false; }
Not all returns can be in ifs public booleancigarParty(int cigars, booleanisWeekend) { if (isWeekend&& 40 <= cigars){ return true; } if(!isWeekend && 40 <= cigars && cigars <= 60){ return true; } if (isWeekend && 40 > cigars){ return false; } if (!isWeekend && (cigars < 40 || cigars > 60)){ return false; } }
Variable Scope public booleancigarParty(int cigars, booleanisWeekend) { if (cigars < 40){ boolean enough = true; } if (!isWeekend && cigars >= 40 && cigars <= 60){ enough = true; } Java doesn’t know this variable!
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!
public booleancigarParty(int cigars, booleanisWeekend) { if(cigars < 40) return false; if (isWeekend) return true; if(cigars <= 60) return true; return false; }