3.4. switch Statements

 

[Page 73]

3.3. 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.

3.3.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 >=




) { 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.


[Page 74]

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 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


==




) 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 neither a compilation error nor a runtime error, it is a logic error. The code in (a) is equivalent to (b) with an empty body.

This error often occurs when you use the next -line block style. Using the end-of-line block style will prevent this error.


3.3.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 .


[Page 75]

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.

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 >=




) { 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 is tested only once.


[Page 76]

3.3.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

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)

{



[Page 77]



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 .



[Page 78]

Tip

If you use an IDE such as JBuilder, NetBeans, or Eclipse, please refer to Learning Java Effectively with JBuilder/NetBeans/Eclipse in the supplements. This supplement shows you how to use a debugger to trace a simple if-else statement.


3.3.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.

Table 3.7. 2002 U.S. Federal Personal Tax Rates
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 ==




) {

// 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

}

[Page 79]


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)
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

filer

, 1-married jointly,\n"


+ 9


"2-married separately, 3-head of household)"


); 10


int


status = Integer.parseInt(statusString); 11 12

// Prompt the user to enter taxable income

13 String incomeString = JOptionPane.showInputDialog( 14


"Enter the taxable income:"


); 15


double


income = Double.parseDouble(incomeString); 16 17

// Compute tax

18



double


tax =




;

19 20



if


(status ==




)

{

// Compute tax for single filers

21


if


(income <=


6000


) 22 tax = income *




.


10


; 23


else if


(income <=


27950


) 24 tax =


6000


*


0.10


+ (income -


6000


) *




.


15


; 25


else if


(income <= 67700) 26 tax =


6000


*


0.10


+ (


27950


-


6000


) *




.


15


+ 27 (income -


27950


) * 0.27; 28


else if


(income <=


141250


) 29 tax =


6000


*




.


10


+ (


27950


-


6000


) *




.


15


+ 30 (


67700


-


27950


) *




.


27


+ (income -


67700


) *




.


30


; 31


else if


(income <=


307050


) 32 tax =


6000


*




.


10


+ (


27950


-


6000


) *




.


15


+ 33 (


67700


-


27950


) *


0.27


+ (


141250


-


67700


) *




.


30


+ 34 (income -


141250


) *




.


35


; 35


else


36 tax =


6000


*




.


10


+ (


27950


-


6000


) *




.


15


+ 37 (


67700


-


27950


) *




.


27


+ (


141250


-


67700


) *




.


30


+ 38 (


307050


-


141250


) *




.


35


+ (income -


307050


) *




.


386


; 39 } 40



else if


(status ==


1


)

{

// Compute tax for married file jointly

41

// Left as exercise

42 }

[Page 80]
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 terminated normally.

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 reports a syntax error.


3.3.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 less-than or equal to 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 .


    [Page 81]
  • 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.

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 }

{% if main.adsdop %}{% include 'adsenceinline.tpl' %}{% endif %}

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 .