Page 176 - Introduction to Programming with Java: A Problem Solving Approach
P. 176
142 Chapter 4 Control Statements
Using the standard definition of the not operator, !, you can apply ! to each of the above comparison opera-
tor conditions and come up with this equivalent condition:
(!(temp < 50) && !(temp > 90))
You can apply basic identity 16 to the above condition and come up with this equivalent condition:
!((temp < 50) || (temp > 90))
You can use the above condition as part of a replacement for Figure 4.5’s original if statement where the if and else subordinate statements are swapped. Here’s the resulting functionally equivalent if statement:
if ((temp < 50) || (temp > 90))
{
}
else
{
}
System.out.println("not OK");
System.out.println("OK");
For another example, consider the condition in the while loop in Figure 4.19, which looks like this:
(!entry.equals("") && !entry.equalsIgnoreCase("q"))
You can apply basic identity 16 to the above condition and come up with this equivalent condition:
Apago PDF Enhancer
!(entry.equals("") || entry.equalsIgnoreCase("q"))
Chapter Summary
• You can alter a program’s sequence of execution by using an if statement. The choice of which of two alternative paths to take is determined by the truth of the if statement’s condition.
• Use the “if, else if” form of the if statement to choose among three or more alternatives.
• You must use braces around two or more subordinate statements within any part of an if statement,
and it’s advisable to use them even when there is only one subordinate statement.
• A condition’s comparison operators (<, >, <=, >=, ==, and !=) have higher priority than its “and” (&&)
and “or” (||) logical operators.
• To negate the result of && and/or || operations, enclose them in parentheses and precede them with a
! operator.
• Use a switch statement to choose among several alternatives on the basis of integer or character
identifiers.
• Use case <number>: or case <character>: and a following break; to delimit each alternative in
a switch statement.
• If the condition in a while loop’s header is true, whatever is in the subsequent block executes, and
then if the condition is still true, that execution repeats.
• A do loop executes its block at least once, and it repeats that execution as long as the condition after the
final while remains true.
• A for loop executes its block as long as the condition in the second component of its header remains
true. The first component in the header initializes a count variable before the first execution, and