IF Statements
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.
1. Simple if Statements
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).
Figure 3.3. An if statement executes statements if the booleanExpression evaluates to true.
If the booleanExpression
evaluates to true, the statements in the block are executed. As an example,
see the following code:
if (radius >= 0) { area = radius * radius * PI; System.out.println("The area for the circle of radius " + radius + " is " + area); }
The flow chart of the
preceding statement is shown in Figure
3.3(b). If the value of radius
is greater than or equal to 0, then the area is computed and the result is displayed; otherwise, the two
statements in the block will not be executed.
Note
The booleanExpression is enclosed in parentheses for all forms of the if statement. Thus, for example, the outer parentheses in the
following if
statements are required.
|
Caution
// Prompt the user to enter an integer String intString = JOptionPane.showInputDialog( "Enter an integer:"); // Convert string into int int number = Integer.parseInt(intString); if (number % 2 == 0) System.out.println(number + " is even."); if (number % 2 != 0) 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.
|
2. if ... else Statements
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 differ
based on whether the condition is true
or false.
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.
Figure 3.4. An if ... else statement executes statements for the true case if the boolean expression evaluates to true; otherwise, statements for the false case are executed.
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 >= 0) { 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
follows:
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 0
is tested only once.
3. Nested if Statements
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, assigns a letter grade to the
variable grade according to the score, with multiple alternatives.
Figure 3.5. A preferred format for multiple alternative if statements is shown in (b).
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 prove to be false. If all of the conditions are false,
the grade becomes 'F'. Note that a condition is tested only when all of the
conditions that come before it are false.
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
Tip
Caution
Tip
4. Example: Computing Taxes
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.
Figure 3.6. The program computes the tax using if statements.
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 == 0) { // 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.
Listing 3.4.
ComputeTaxWithSelectionStatement.java
(This item is displayed on pages 79 - 80 in the print version)
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 0 indicates that the program is terminated normally.
Note
5. Example: An Improved Math Learning Tool
This example creates a program for a first
grader to practice subtraction. The program randomly generates two single-digit
integers number1
and number2
with number1
> number2 and displays a question such
as "What
is 9-2?" to the student, as shown in Figure 3.7(a). After the student
types the answer in the input dialog box, the program displays a message dialog
box to indicate whether the answer is correct, as shown in Figure 3.7(b).
Figure 3.7. The program generates a subtraction question and grades the student's answer.
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
0
and 9).
The program may work as follows:
-
Generate two single-digit integers into number1 and number2.
-
If number1 < number2, swap number1 with number2.
The complete program is shown in Listing 3.5.
Listing 3.5. SubtractionTutor.java
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 variables number1
and number2,
a temporary variable temp (line 11) is used to first hold the value in number1. The value in number2
is assigned to number1
(line 12), and the value in temp
is assigned to number2.
IF YOU HAVE TROUBLE, YOU CAN TOLD ME
No comments:
Post a Comment