5.5 Methods that Return boolean Values
A particularly effective way of improving the clarity of programs is through
the use of boolean methods - queries that return either true or false.
Often the boolean expressions that control selection or repetition statements
are quite complex. Trying to read through such an expression can
cause a reader to get caught up in details and lose track of the flow of
the program. If a boolean method with some descriptive identifier is used
in place of such an expression, the resulting code should be much easier
to follow. An identifier of a boolean method usually begins with "is",
indicating that the value returned by the method is the answer to some
true/false question.
Example 1
The fragment
if (13 <= age && age <= 19)
could be replaced by
if (isTeen(age))
where isTeen is a method whose definition could be
public static boolean isTeen (int n)
{
if (n >= 13 && n <= 19)
return true;
else
return false;
}
|
|
In Example 1, the value returned by the method is always identical to
the value of the expression n >= 13 && n <= 19. We can take advantage
of this to make the definition of the method more concise, as follows.
public static boolean isTeen (int n)
{
return >= 13 && n <= 19;
}
|
|
Exercise 5.5
-
Write boolean methods that could be used to make each fragment
more readable.
(a) while (n % 2 1)
.
.
(b) if ('0' <= c && c <= '9')
.
.
(c) do
.
.
while (nextChar =='.' || nextChar ==',' ||
nextChar == '?' || nextChar == ':' ||
nextChar == ';' || nextChar == '!');
-
Write a boolean method isDi visible with two int parameters. The
method should return true if and only if the first parameter value is
exactly divisible by the second.
-
Write a boolean method isLetter that returns true if and only if its
single char parameter is a letter of the alphabet (either upper case
or lower case).
-
Write a boolean method isPrime that returns true if and only if its
int parameter is a prime number.
-
Write two boolean methods, both called isPass, that could be used
with the following fragment.
System.out.println("Letter Grade? (y/n)");
char response = In.getChar();
System.out.println("Value of grade?");
if (response == 'y')
{
char mark = In.getChar();
if (isPass(mark))
System.out.println("Pass");
}
else // assume numerical grade
{
int mark = In.getlnt();
if (isPass(mark))
System.out.println("Pass");
}
|
|
The methods should return true if and only if the mark is a pass (at
least 'D' for a letter grade and at least 50 for a numerical grade).
| |