Last notes on if statements

advertisement
The Fine Points of Conditionals
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
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)
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…
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;
}
Error:
}
return false;
Unreachable
System.out.println(“Done”);
code
}
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;
}
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 < 40 || cigars > 60)){
return false;
}
}
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!
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 boolean cigarParty(int cigars,
boolean isWeekend) {
if(cigars < 40)
return false;
if (isWeekend)
return true;
if(cigars <= 60)
return true;
return false;
}
Download