The example in Listing 3.3 displays a message such as "6 + 2 = 7 is false." If you wish the message to be "6 + 2 = 7 is incorrect," you have to use a selection statement .
This section introduces selection statements. Java has several types of selection statements: simple if statements, if ... else statements, nested if statements, switch statements, and conditional expressions.
A simple if statement executes an action if and only if the condition is true . The syntax for a simple if statement is shown below:
if
(booleanExpression) { statement(s); }
The execution flow chart is shown in Figure 3.3(a).
If the booleanExpression evaluates to true , the statements in the block are executed. As an example, see the following code:
if (radius >= ) { area = radius * radius * PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); }
The flow chart of the
Note
|
|
The
booleanExpression
is
The braces can be omitted if they enclose a single statement. |
Caution
|
|
Forgetting the braces when they are needed for grouping multiple statements is a common programming error. If you modify the code by adding new statements in an if statement without braces, you will have to insert the braces if they are not already in place. |
The following statement determines whether a number is even or odd:
// Prompt theuser to enter an integer String intString = JOptionPane.showInputDialog( "Enter an integer:" ); // Convert string into int int number = Integer.parseInt(intString); if (number % 2 == ) System.out.println(number + " is even." ); if (number % 2 != ) System.out.println(number + " is odd." );
Caution
|
|
Adding a semicolon at the end of an if clause, as shown in (a) in the following code, is a common mistake.
This mistake is hard to find because it is
This error often occurs when you use the
|
A simple
if
statement takes an action if the specified condition is
true
. If the condition is
false
, nothing is done. But what if you want to take alternative actions when the condition is
false
? You can use an
if ... else
statement. The actions that an
if ... else
statement specifies
Here is the syntax for this type of statement:
if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; }
The flow chart of the statement is shown in Figure 3.4.
If the booleanExpression evaluates to true , the statement(s) for the true case is executed; otherwise, the statement(s) for the false case is executed. For example, consider the following code:
if (radius >= ) { area = radius * radius * PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } else { System.out.println( "Negative input" ); }
If radius >= 0 is true , area is computed and displayed; if it is false , the message "Negative input" is printed.
As usual, the braces can be omitted if there is only one statement within them. The braces enclosing the System.out.println("Negative input") statement can therefore be omitted in the preceding example.
Using the
if else
statement, you can rewrite the code for determining whether a number is even or odd in the preceding section, as
if (number % 2 == 0 ) System.out.println(number + " is even." ); else System.out.println(number + " is odd." );
This is more efficient because whether
number % 2
is
is
The statement in an if or if ... else statement can be any legal Java statement, including another if or if ... else statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement can contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the following is a nested if statement:
if (i > k) { if (j > k) System.out.println( "i and j are greater than k" ); } else System.out.println( "i is less than or equal to k" );
The if (j > k) statement is nested inside the if (i > k) statement.
The nested
if
statement can be used to implement multiple alternatives. The statement given in Figure 3.5(a), for instance,
The execution of this
if
statement proceeds as follows. The first condition
(score >= 90.0)
is tested. If it is
true
, the grade becomes
'A'
. If it is
false
, the second condition
(score >= 80.0)
is tested. If the second condition is
true
, the grade becomes
'B'
. If that condition is
false
, the third condition and the rest of the conditions (if necessary) continue to be tested until a condition is met or all of the conditions
The if statement in Figure 3.5(a) is equivalent to the if statement in Figure 3.5(b). In fact, Figure 3.5(b) is the preferred writing style for multiple alternative if statements. This style avoids deep indentation and makes the program easy to read.
Note
|
|
The else clause matches the most recent unmatched if clause in the same block. For example, the following statement in (a) is equivalent to the statement in (b). The compiler ignores indentation. Nothing is printed from the statements in (a) and (b). To force the else clause to match the first if clause, you must add a pair of braces:
int i = 1 ; int j = 2 ; int k = 3 ; if ( i > j) {
if (i > k) System.out.println( "A" ); } else System.out.println( "B" ); This statement prints B . |
Tip
|
|
Often new programmers write the code that assigns a test condition to a boolean variable like the code in (a):
The code can be simplified by assigning the test value directly to the variable, as shown in (b). |
Caution
|
|
To test whether a boolean variable is true or false in a test condition, it is redundant to use the equality comparison operator like the code in (a):
Instead, it is better to use the boolean variable directly, as shown in (b). Another good reason to use the boolean variable directly is to avoid errors that are difficult to detect. Using the operator instead of the == operator to compare equality of two items in a test condition is a common error. It could lead to the following erroneous statement:
if (even = true ) System.out.println( "It is even." ); This statement does not have syntax errors. It assigns true to even so that even is always true . |
Tip
|
|
If you use an IDE such as JBuilder, NetBeans, or Eclipse,
|
This section uses nested if statements to write a program to compute personal income tax. The United States federal personal income tax is calculated based on filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3.7. If you are, say, single with a taxable income of $10,000, the first $6,000 is taxed at 10% and the other $4,000 is taxed at 15%. So your tax is $1,200.
| Tax rate | Single filers | Married filing jointly or qualifying widow/widower | Married filing separately | Head of household |
|---|---|---|---|---|
| 10% | Up to $6,000 | Up to $12,000 | Up to $6,000 | Up to $10,000 |
| 15% | $6,001 “$27,950 | $12,001 “$46,700 | $6,001 “$23,350 | $10,001 “$37,450 |
| 27% | $27,951 “$67,700 | $46,701 “$112,850 | $23,351 “$56,425 | $37,451 “$96,700 |
| 30% | $67,701 “$141,250 | $112,851 “$171,950 | $56,426 “$85,975 | $96,701 “$156,600 |
| 35% | $141,251 “$307,050 | $171,951 “$307,050 | $85,976 “$153,525 | $156,601 “$307,050 |
| 38.6% | $307,051 or more | $307,051 or more | $153,526 or more | $307,051 or more |
Your program should prompt the user to enter the filing status and taxable income and computes the tax for the year 2002. Enter 0 for single filers, 1 for married filing jointly, 2 for married filing separately, and 3 for head of household. A sample run of the program is shown in Figure 3.6.
Your program computes the tax for the taxable income based on the filing status. The filing status can be determined using if statements outlined as follows:
if (status == ) { // Compute tax for single filers } else if (status == 1 ) { // Compute tax for married file jointly } else if (status == 2 ) { // Compute tax for married file separately }
else if (status == 3 ) { // Compute tax for head of household } else { // Display wrong status }
For each filing status, there are six tax rates. Each rate is applied to a certain amount of taxable income. For example, of a taxable income of $400,000 for single filers, $6,000 is taxed at 10%, (27950 “ 6000) at 15%, (67700 “ 27950) at 27%, (141250 “ 67700) at 35%, and (400000 “ 307050) at 38.6%.
Listing 3.4 gives the solution to compute taxes for single filers. The complete solution is left as an exercise.
1 import javax.swing.JOptionPane; 2 3 public class ComputeTaxWithSelectionStatement { 4 public static void main(String[] args) { 5 // Prompt the user to enter filing status 6 String statusString = JOptionPane.showInputDialog( 7 "Enter the filing status:\n" + 8 "(0-single 43 else if (status == 2 ) { // Compute tax for married separately 44 // Left as exercise 45 } 46 else if (status == 3 ) { // Compute tax for head of household 47 // Left as exercise 48 } 49 else { 50 System.out.println( "Error: invalid status" ); 51 System.exit( ); 52 } 53 54 // Display the result 55 JOptionPane.showMessageDialog( null , "Tax is " + 56 ( int )(tax * 100 ) / 100 . ); 57 } 58 } |
The import statement (line 1) makes the class javax.swing.JOptionPane available for use in this example.
The program receives the filing status and taxable income. The multiple alternative if statements (lines 22, 42, 45, 48, 51) check the filing status and compute the tax based on the filing status.
Like the
showMessageDialog
method,
System.exit(0)
(line 53) is also a static method. This method is defined in the
System
class. Invoking this method terminates the program. The argument
indicates that the program is
Note
|
|
An initial value of
is assigned to
tax
(line 20). A syntax error would occur if it had no initial value because all of the other statements that assign values to
tax
are within the
if
statement. The compiler thinks that these statements may not be executed and therefore
|
This example creates a program for a first
To generate a random number, use the
random()
method in the
Math
class. Invoking this method returns a random double value
d
such that
0.0
d < 1.0
So
(int)(Math.random() *10)
returns a random single-digit integer (i.e., a number between
and
9
).
The program may work as follows:
Generate two single-digit integers into number1 and number2 .
If number1 < number2 , swap number1 with number2 .
Prompt the student to answer "what is number1 “ number2?"
Check the student's answer and display whether the answer is correct.
The complete program is shown in Listing 3.5.
1 import javax.swing.JOptionPane; 2 3 public class SubtractionTutor { 4 public static void main(String[] args) { 5 // 1. Generate two random single-digit integers 6 int number1 = ( int )(Math.random() * 10 ); 7 int number2 = ( int )(Math.random() * 10 ); 8 9 // 2. If number1 < number2, swap number1 with number2 10 if (number1 < number2) { 11 int temp = number1; 12 number1 = number2; 13 number2 = temp; 14 } 15 16 // 3. Prompt the student to answer "what is number1 “ number2?" 17 String answerString = JOptionPane.showInputDialog 18 ( "What is " + number1 + " - " + number2 + "?" ); 19 int answer = Integer.parseInt(answerString); 20 21 // 4. Grade the answer and display the result 22 String replyString; 23 if (number1 - number2 == answer) 24 replyString = "You are correct!" ; 25 else 26 replyString = "Your answer is wrong.\n" + number1 + " - " 27 + number2 + " should be " + (number1 - number2); 28 JOptionPane.showMessageDialog( null , replyString); 29 } 30 } |
To swap two