Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 Control Statements

Similar presentations


Presentation on theme: "Chapter 5 Control Statements"— Presentation transcript:

1 Chapter 5 Control Statements
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved

2 Objectives To understand the flow of control in selection and loop statements. To use Boolean expressions to control selection statements and loop statements. To implement selection control using if and nested if statements. To implement selection control using switch statements. To write expressions using the conditional operator. To use while, do-while, and for loop statements to control the repetition of statements. To write nested loops. To know the similarities and differences of three types of loops. To implement program control with break and continue. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved

3 Selection Statements if Statements switch Statements
Conditional Operators

4 Example Example if the radius is positive
computes the area and display result;

5 Simple if Statements if (radius >= 0) {
area = radius * radius * PI; System.out.println("The area" “ for the circle of radius " + "radius is " + area); } if (booleanExpression) { statement(s); }

6 Note

7 Comparison Operators Operator Name < less than
<= less than or equal to > greater than >= greater than or equal to == equal to != not equal to

8 Boolean Operators Operator Name ! not && and || or ^ exclusive or

9 Truth Table for Operator !

10 Truth Table for Operator &&

11 Truth Table for Operator ||

12 Truth Table for Operator ^

13 Write the output of the following program:
public class TestBoolean { public static void main (String[] args) { int number = 18; System.out.println(“Is ” + number + “:” + “\ndivisible by 2 and 3? ” + (number % 2 == 0 && number % 3 == 0) + “\ndivisible by 2 or 3? ” + (number % 2 == 0 || number % 3 == 0) + “\ndivisible by 2 or 3, but not both? ” + (number % 2 == 0 ^ number % 3 == 0)); }

14 TestBoolean program output:

15 The & and | Operators &&: conditional AND operator
&: unconditional AND operator exp1 && exp2 (1 < x) && (x < 100) (1 < x) & (x < 100)

16 The & and | Operators ||: conditional OR operator
|: unconditional OR operator exp1 && exp2 (1 < x) || (x < 100) (1 < x) | (x < 100)

17 The & and | Operators p1 && p2, Java first evaluates p1 and then evaluates p2 if p1 is true; if p1 is false, it does not evaluate p2. p1 || p2, Java first evaluates p1 and then evaluates p2 if p1 is false; if p1 is true, it does not evaluate p2. For & and | operators, & same as && and | same as || BUT & and | are evaluated for both operands.

18 The & and | Operators: Exercise
1.If x is 1, what is x after the evaluation of the following expression? (x > 1) & (x++ > 1) 2.If x is 1, what is x after the evaluation of the following expression? (x > 1) && (x++ > 1)

19 Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. Wrong

20 Leap Year? A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400. The source code of the program is given below. boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);

21 Finding Leap Year Leap Year program: import javax.swing.JOptionPane;
public class LeapYear { public static void main(String args[]) { // Prompt the user to enter a year String yearString = JOptionPane.showInputDialog("Enter a year"); // Convert the string into an int value int year = Integer.parseInt(yearString); // Check if the year is a leap year boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); // Display the result in a message dialog box JOptionPane.showMessageDialog(null, year + " is a leap year? " + isLeapYear); } Output:

22 The if...else Statement if (booleanExpression) {
statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case;

23 if...else Example if (radius >= 0) {
area = radius * radius * ; System.out.println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input");

24 Multiple Alternative if Statements
Program example:

25 Note The else clause matches the most recent if clause in the same block. What is the output of the above program statement?

26 Note, cont. Nothing is printed from the preceding statement. 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.

27 TIP Program example:

28 CAUTION Program example:

29 Example: Computing Taxes
The US federal personal income tax is calculated based on the 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 below. The if…else structure: 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

30 Example: Computing Taxes
Algorithm: 1. Read status and income. 2. Compute tax based on status. if (status==0) { // Compute tax for single filers if (income<6000) tax=incomeX0.10; else if (income<=27950) tax=6000X0.10+(income-6000)*0.15; . else tax=6000X0.10+( )X0.15+( )X0.27+( )X0.30+( )*0.35+(income )X0.368 } 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 3. Display tax. Refer ComputeTaxWithSelectionStatement.java page 105, Liang Text Book for the Java program

31 switch Statements switch (status) {
case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; case 2: compute taxes for married file separately; case 3: compute taxes for head of household; default: System.out.println("Errors: invalid status"); System.exit(0); }

32 switch Statement Flow Chart

33 switch Statement Rules
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; case valueN: statement(s)N; default: statement(s)-for-default; } The value1, ..., and valueN must have the same data type as the value of the switch-expression. The resulting statements in the case statement are executed when the value in the case statement matches the value of the switch-expression. Note that value1, ..., and valueN are constant expressions, meaning that they cannot contain variables in the expression, such as 1 + x.

34 switch Statement Rules
The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; case valueN: statement(s)N; default: statement(s)-for-default; } The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The case statements are executed in sequential order, but the order of the cases (including the default case) does not matter. However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

35 switch Example

36 switch Example switch (ch) { case ‘a’: System.out.println(ch);
case ‘b’: System.out.println(ch); case ‘c’: System.out.println(ch); } What is the output of the above program segment if ch is ‘a’?

37 Conditional Operator Program example: if (x > 0) y = 1 else y = -1;
is equivalent to (booleanExp) ? exp1 : exp2 y = (x > 0) ? 1 : -1; (booleanExpression) ? expression1 : expression2 Program example:

38 Conditional Operator The statement: if (num % 2 == 0)
System.out.println(num + “is even”); else System.out.println(num + “is odd”); is equivalent to the statement: System.out.println((num % 2 == 0)? num + “is even” : num + “is odd”); Program example:

39 Operator Precedence and Associativity
Operator precedence and associativity determine the order in which operators are evaluated.

40 Operator Precedence var++, var– (Postfix)
+, - (Unary plus and minus), ++var,--var (Prefix) (type) Casting ! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==, !=; (Equality) & (Unconditional AND) ^ (Exclusive OR) | (Unconditional OR) && (Conditional AND) Short-circuit AND || (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator)

41 Operator Precedence and Associativity
The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule. If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative.

42 Operator Associativity
When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to  ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5))

43 Operator Precedence How to evaluate * 4 > 5 * (4 + 3) – 1?

44 Example Applying the operator precedence and associativity rule, the expression * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

45 Operand Evaluation Order
The precedence and associativity rules specify the order of the operators, but do not specify the order in which the operands of a binary operator are evaluated. Operands are evaluated from left to right in Java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated.

46 Operand Evaluation Order, cont.
If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code, because a is evaluated to 0 before ++a is evaluated to 1.  int a = 0; int x = a + (++a); But x becomes 2 in the following code, because ++a is evaluated to 1, then a is evaluated to 1. int x = ++a + a;

47 Rule of Evaluating an Expression
· Rule 1: Evaluate whatever sub-expressions you can possibly evaluate from left to right. · Rule 2: The operators are applied according to their precedence. · Rule 3: The associativity rule applies for two operators next to each other with the same precedence.

48 Rule of Evaluating an Expression
·  Applying the rule, the expression * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

49 Repetitions while Loops do-while Loops for Loops break and continue

50 while Loop Flow Chart while (loop-continuation-condition) {
int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; } while (loop-continuation-condition) { // loop-body; Statement(s); }

51 Write an algorithm and a program that counts the sum of several input data and exit if input data is 0 ALGORITHM: Start the processing Read data 3. Convert data to integer number 4. Initialize sum = 0 5. Repeat reading until data = 0 5.1 Calculate sum 5.2 Read next data Print sum Stop the processing PROGRAM: import javax.swing.JOptionPane; public class SumIntegers { public static void main(String[] args) { String dataString = JOptionPane.showInputDialog ("Enter an int value:\n(the program exits if the input is 0)"); int data = Integer.parseInt(dataString); int sum = 0; while (data != 0) { sum = sum + data; dataString = JOptionPane.showInputDialog data = Integer.parseInt(dataString); } JOptionPane.showMessageDialog(null, "The sum is "+ sum); OUTPUT:

52 Caution Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0. // data should be zero double data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero"); else System.out.println("data is not zero");

53 Exercise Write an algorithm and a program using the while loop that prints the numbers from 1 to 100. Program output: 1 2 3 ….. 100 Write an algorithm and a program using the while loop to get the sum of 1 to 100 integer numbers ( ). Program output: Sum of 1 to 100 = 5050

54 do-while Loop do { // Loop body; Statement(s);
} while (loop-continuation-condition);

55 A program that counts the sum of several input data and exit if input data is 0
import javax.swing.JOptionPane; public class SumIntegers { public static void main(String[] args) { String dataString = JOptionPane.showInputDialog ("Enter an int value:\n(the program exits if the input is 0)"); int data = Integer.parseInt(dataString); int sum = 0; do { sum = sum + data; dataString = JOptionPane.showInputDialog data = Integer.parseInt(dataString); } while (data!=0); JOptionPane.showMessageDialog(null, "The sum is "+ sum); }

56 Exercise Write an algorithm and a program using the do…while loop that prints numbers from 100 to 1. Program output: 100 99 98 ….. 1 Write an algorithm and a program using the do…while loop to get the sum of odd numbers from 1 to 99 ( ). Program output: Sum of odd numbers from 1 to 99 = 2500

57 for Loops for (initial-action; loop-continuation-condition; action-after-each-iteration) { // loop body; Statement(s); } int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java!"); }

58 Note The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however. for (int i = 1; i < 100; System.out.println(i++)); // prints 1-99 for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something }

59 Note If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, I recommend that you use the equivalent loop in (b) to avoid confusion:

60 Example Using for Loops
Problem: Write a program that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: and so on. import javax.swing.JOptionPane; public class TestSum{ public static void main(String[] args) { float sum = 0; for (float i = 0.01f; i <= 1.0f; i = i f) sum = sum + i; JOptionPane.showMessageDialog(null, "The sum is " + sum); }

61 Exercise Write a program using the for loop that prints the numbers from 0.1 to 1.0. Program Output: Write a program using the for loop to get the sum of 0.1 to 1.0 integer numbers ( ). Program Output: Sum from 0.1 to 1.0 = 5.5

62 Which Loop to Use? The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (A) in the following figure can always be converted into the following for loop in (B): Example: Convert the following while loop into a for loop: int i=1; int sum=0; while (sum<10000) { sum=sum+i; i++; } int sum=0; for (int i=1;sum<10000;i++) sum=sum+i; System.out.println(sum); convert while to for

63 Which Loop to Use? Exercise: Convert the following while loop into a for loop: int i=0; long sum=0; while (i<=1000) { sum=sum+i; i++; }

64 Which Loop to Use? Solution: Convert the following while loop into a for loop: int i=0; long sum=0; while (i<=1000) { sum=sum+i; i++; } long sum=0; for (int i=0;i<=1000;i++) sum=sum+i; convert while to for

65 Which Loop to Use? A for loop in (A) in the following figure can generally be converted into the following while loop in (B) except in certain special cases (will be discussed when learning continue keyword, related to review question 4.12):

66 Recommendations I recommend that you use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.

67 Caution Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below: for (int i=0; i<10; i++); { System.out.println("i is " + i); } Logic Error

68 Caution, cont. Similarly, the following loop is also wrong:
int i=0; while (i < 10); { System.out.println("i is " + i); i++; } In the case of the do loop, the following semicolon is needed to end the loop. do { } while (i<10); Logic Error Correct

69 Displaying the Multiplication Table
Problem: Write a program that uses nested for loops to print a multiplication table. public class Mult { public static void main (String[] args) { for (int i=1; i<=9; i++) { System.out.print("\n" +i); for (int j=1; j<=9; j++) System.out.print("\t" +(i*j)); System.out.println(""); } Output:

70 Exercise Using nested loop, write a program to produce the following output:

71 The break Keywords break immediately ends the
innermost loop that contains it. It is generally used with an if statement

72 The continue Keyword continue only ends the current
iteration. Program control goes to the end of the loop body. The keyword is usually used with an if statement.

73 Using break and continue
Examples for using the break and continue keywords: TestBreak.java TestContinue.java

74 public class TestBreak {
public static void main(String[] args) { int sum = 0, number = 0; while (number < 5) { number++; sum += number; if (sum >= 6) break; } System.out.println(“The number is “ + number); System.out.println(“The sum is “ + sum);

75 public class TestContinue {
public static void main(String[] args) { int sum = 0, number = 0; while (number < 5) { number++; if (number % 2 == 0) continue; sum += number; } System.out.println(“The number is “ + number); System.out.println(“The sum is “ + sum);

76 Converting for to while for Special Cases
A for loop in (A) in the following figure can generally be converted into the following while loop in (B) except in certain special cases (see Review Question 4.12 for one of them): Example (based on Review Question 4.12, pg. 146): (2) public class Converted1 { public static void main (String args[]) { int sum=0, i=0; while (i<4) { if (i%3==0) { i++; continue; } sum+=i; System.out.println(sum); (1) public class Original { public static void main (String args[]) { int sum=0; for (int i=0;i<4;i++) { if (i%3==0) continue; sum+=i; } System.out.println(sum); Converted Correct Conversion Output for (1) and (2) is 3

77 Example Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2.

78 import javax.swing.JOptionPane;
public class GreatestCommonDivisor { /** Main method */ public static void main(String[] args) { // Prompt the user to enter two integers String s1 = JOptionPane.showInputDialog("Enter first integer"); int n1 = Integer.parseInt(s1); String s2 = JOptionPane.showInputDialog("Enter second integer"); int n2 = Integer.parseInt(s2); int gcd = 1; int k = 1; while (k <= n1 && k <= n2) { if (n1 % k == 0 && n2 % k == 0) gcd = k; k++; } String output = "The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd; JOptionPane.showMessageDialog(null, output);

79 Finding the Sales Amount
Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate. Sales Amount Commission Rate $0.01–$5, percent $5,000.01–$10, percent $10, and above 12 percent Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000. Since your base salary is $5,000, you have to make $25,000 in commissions to earn $30,000 a year. What is the sales amount for a $25,000 commission? You can find it if you know the sales amount.

80 import javax.swing.JOptionPane;
public class FindSalesAmount { /** Main method */ public static void main(String[] args) { // The commission sought final double COMMISSION_SOUGHT = 25000; final double INITIAL_SALES_AMOUNT = 0.01; double commission = 0; double salesAmount = INITIAL_SALES_AMOUNT; do { // Increase salesAmount by 1 cent salesAmount += 0.01; // Compute the commission from the current salesAmount; if (salesAmount >= ) commission = 5000 * * (salesAmount ) * 0.12; else if (salesAmount >= ) commission = 5000 * (salesAmount ) * 0.10; else commission = salesAmount * 0.08; } while (commission < COMMISSION_SOUGHT); // Display the sales amount String output = "The sales amount $" + (int)(salesAmount * 100) / "\nis needed to make a commission of $" + COMMISSION_SOUGHT; JOptionPane.showMessageDialog(null, output); }

81 Exercise Write a program that reads an unspecified number of positive integers, counts the number of integers and finds the biggest and smallest integer value. Your program ends with the input Use the while loop. An output example:

82 SOLUTION import java.util.Scanner; public class Counting {
public static void main (String args[]) int counter=0, biggest=0, smallest=0; Scanner scan=new Scanner(System.in); System.out.print("Enter a positive integer: "); int number=scan.nextInt(); while (number!=-999) counter++; if (number > biggest) biggest=number; if (number < biggest) smallest=number; number=scan.nextInt(); } System.out.println("Number of integers = " + counter); System.out.println("Biggest integer = " + biggest); System.out.println("Smallest integer = " + smallest);

83 Exercise Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score. Use the do…while loop. An output example:

84 SOLUTION import javax.swing.JOptionPane; public class Student {
public static void main (String args[]) int input; int counter=0; int number; int largest = 0; String name=" "; String student=" "; input = Integer.parseInt(JOptionPane.showInputDialog("Enter number of students: ")); do counter++; name = JOptionPane.showInputDialog("Enter student's name: "); number = Integer.parseInt(JOptionPane.showInputDialog("Enter student's score: ")); if (number >= largest) { largest=number; student=name; } }while (counter<input); JOptionPane.showMessageDialog(null, "The highest score is " + student +" with the score " +largest);

85 CASE STUDY: ALGORITHM set discountprice, totalprice to 0.0 read code
while (code!=-999) { 3.1 if code 1, display ‘Food category’ else if code 2, display ‘Water category’ else if code 3, display ‘Magazine category’ else if code 4, display ‘Stationery category’ else if code 5, display ‘Toys category’ else { display ‘Your input is incorrect!’ ends current iteration } 3.2 read price 3.3 read quantity 3.4 switch (code) { case 1: discountprice=(price-0.1*price))*quantity case 2: discountprice=(price-0.2*price))*quantity case 3: discountprice=(price-0.3*price))*quantity case 4: discountprice=(price-0.4*price))*quantity case 5: discountprice=(price-0.5*price))*quantity default: discountprice=(price-0.0*price))*quantity 3.5 totalprice=totalprice+discountprice 3.6 read next code Print totalprice 85

86 CASE STUDY: PROGRAM 86 /* Read price */ import java.util.Scanner;
System.out.print("Enter price: $"); double price = scanner.nextDouble(); System.out.println(); /* Read quantity */ System.out.print("Enter quantity: "); int quantity = scanner.nextInt(); /* Calculate discountprice */ switch (code) { case 1: discountprice=(price-(0.1*price))*quantity; break; case 2: discountprice=(price-(0.2*price))*quantity; case 3: discountprice=(price-(0.3*price))*quantity; case 4: discountprice=(price-(0.4*price))*quantity; case 5: discountprice=(price-(0.5*price))*quantity; default: discountprice=(price-(0.0*price))*quantity; System.exit(0); } //end switch /* Calculate totalprice */ totalprice=totalprice+discountprice; /* Enter next code */ System.out.print("Enter code: "); code = scanner.nextInt(); } //end while System.out.println("The totalprice is $" +totalprice); // print result } //end main } //end class import java.util.Scanner; public class CashRegisterLooping { public static void main (String[] args) { /* Initializations */ double discountprice=0.0; double totalprice=0.0; /* Create scanner object */ Scanner scanner = new Scanner(System.in); /* Primer read */ System.out.print("Enter code: "); int code = scanner.nextInt(); System.out.println(); while (code!=-999) { if (code==1) System.out.println("Food category"+"\n"); else if (code==2) System.out.println("Water category"+"\n"); else if (code==3) System.out.println("Magazine category"+"\n"); else if (code==4) System.out.println("Stationery category"+"\n"); else if (code==5) System.out.println("Toys category"+"\n"); else { System.out.println("Your input is incorrect!"+"\n"); code = scanner.nextInt(); continue; } //end else 86


Download ppt "Chapter 5 Control Statements"

Similar presentations


Ads by Google