|
Boolean Methods
A Programming Pattern |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
void, have
it return true on success and false
on failure
public static boolean printSquareRoot(double x)
{
boolean ok;
double squareRoot;
if (x >= 0.)
{
squareRoot = Math.sqrt(x);
JMUConsole.printf("The root of %f is %f.\n", x, squareRoot);
ok = true;
}
else
{
ok = false;
}
return ok;
}
if (((dieOne + dieTwo) == 7) || ((dieOne + dieTwo) == 11))
{
// Make Payout
}
if (wins(dieOne, dieTwo))
{
// Make Payout
}
public static boolean wins(int dieOne, int dieTwo)
{
boolean result;
int total;
total = dieOne + dieTwo;
if ((total == 7) || (total == 11)) result = true;
else result = false;
return result;
}
public static boolean wins(int dieOne, int dieTwo)
{
int total;
total = dieOne + dieTwo;
return ((total == 7) || (total == 11));
}
isOdd(x) is much easier to read and understand than
((x % 2) == 1)
if (height >= 62)
{
if (sex == 'M')
{
// Case 1
}
else
{
// Case 2
}
}
else
{
if (sex == 'M')
{
// Case 3
}
else
{
// Case 4
}
}
'M' and 'm'
if (height >= 62)
{
if ((sex == 'M') || (sex == 'm'))
{
// Case 1
}
else
{
// Case 2
}
}
else
{
if ((sex == 'M') || (sex == 'm'))
{
// Case 3
}
else
{
// Case 4
}
}
if (height >= 62)
{
if (isMale(sex)) // Case 1
else // Case 2
}
else
{
if (isMale(sex)) // Case 3
else // Case 4
}
public static boolean isMale(char sex)
{
return (sex == 'M');
}
public static boolean isMale(char sex)
{
return ((sex == 'M') || (sex == 'm'));
}
isOdd() and
isEven())(x%2) == 1 in isOdd()
and (x%2) == 0
in isEven())isEven() return !isOdd())
public static boolean isLowIncome(double income)
{
return (income < 20000.0);
}
public static boolean isMiddleIncome(double income)
{
return ((income >= 20000.0) && (income < 75000.0));
}
public static boolean isHighIncome(double income)
{
return (income >= 75000.0);
}
public static boolean isLowIncome(double income)
{
return (income < 20000.0);
}
public static boolean isMiddleIncome(double income)
{
return ((!isLowIncome()) && (income < 75000.0));
}
public static boolean isHighIncome(double income)
{
return (!isLowIncome(income) && !isMiddleIncome(income));
}
boolean
(i.e., true or false)
public static boolean isPassing(int grade)
{
return grade>=60;
}
public static int creditsEarned(int grade, int creditsPossible)
{
if (isPassing(grade)) return creditsPossible;
else return 0;
}
public static int isPassing(int grade)
{
return grade/60;
}
public static int creditsEarned(double grade, int creditsPossible)
{
return isPassing(grade)*creditsPossible;
}