Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-61 Chapter 5 Control Statements.

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-61 Chapter 5 Control Statements."— Presentation transcript:

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

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

3 3 Selection Statements  if Statements  switch Statements F Conditional Operators

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

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

6 6 Note

7 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 8 Boolean Operators Operator Name ! not && and || or ^ exclusive or

9 9 Truth Table for Operator !

10 10 Truth Table for Operator &&

11 11 Truth Table for Operator ||

12 12 Truth Table for Operator ^

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

14 14 TestBoolean program output:

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

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

17 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 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 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 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 21 Finding Leap Year 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: Leap Year program:

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

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

24 24 Multiple Alternative if Statements Program example:

25 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 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 27 TIP Program example:

28 28 CAUTION Program example:

29 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. 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 } The if…else structure:

30 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+(29500-6000)X0.15+(67700-27950)X0.27+(141250-67700)X0.30+(307050-141250)*0.35+(income-307050)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 31 switch Statements switch (status) { case 0: compute taxes for single filers; break; case 1: compute taxes for married file jointly; break; case 2: compute taxes for married file separately; break; case 3: compute taxes for head of household; break; default: System.out.println("Errors: invalid status"); System.exit(0); }

32 32 switch Statement Flow Chart

33 33 switch Statement Rules switch (switch-expression) { case value1: statement(s)1; break; case value2: statement(s)2; break; … case valueN: statement(s)N; break; default: statement(s)-for-default; } The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. 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 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; break; … case valueN: statement(s)N; break; 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 35 switch Example

36 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 37 Conditional Operator 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 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 39 Operator Precedence and Associativity Operator precedence and associativity determine the order in which operators are evaluated.

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

41 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 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 43 Operator Precedence How to evaluate 3 + 4 * 4 > 5 * (4 + 3) – 1?

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

45 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 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 a = 0; int x = ++a + a;

47 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 48 Rule of Evaluating an Expression · Applying the rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

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

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

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

52 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 53 Exercise F Write an algorithm and a program using the while loop that prints the numbers from 1 to 100. Program output: 1 2 3 ….. 100 F Write an algorithm and a program using the while loop to get the sum of 1 to 100 integer numbers ( 1+2+3+..+100). Program output: Sum of 1 to 100 = 5050

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

55 55 1. import javax.swing.JOptionPane; 2. public class SumIntegers { 3. public static void main(String[] args) { 4. String dataString = JOptionPane.showInputDialog 5. ("Enter an int value:\n(the program exits if the input is 0)"); 6. int data = Integer.parseInt(dataString); 7. int sum = 0; 8. do { 9. sum = sum + data; 10. dataString = JOptionPane.showInputDialog 11. ("Enter an int value:\n(the program exits if the input is 0)"); 12. data = Integer.parseInt(dataString); 13. } while (data!=0); 14. JOptionPane.showMessageDialog(null, "The sum is "+ sum); 15. } 16. } A program that counts the sum of several input data and exit if input data is 0

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

57 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 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 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 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: 0.01 + 0.02 + 0.03 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 + 0.01f) sum = sum + i; JOptionPane.showMessageDialog(null, "The sum is " + sum); }

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

62 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 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 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 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 in Liang text book):

66 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 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 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. int i=0; do { System.out.println("i is " + i); i++; } while (i<10); Logic Error Correct

69 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: 1123456789 224...... 18 336...... 27 448...... 36 5510...... 45 6612...... 54 7714...... 63 8816...... 72 9918...... 81

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

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

72 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 73 Using break and continue Examples for using the break and continue keywords: F TestBreak.java F TestContinue.java

74 74 1. public class TestBreak { 2. public static void main(String[] args) { 3. int sum = 0, number = 0; 4. while (number < 5) { 5. number++; 6. sum += number; 7. if (sum >= 6) 8. break; 9. } 10. System.out.println(“The number is “ + 11. number); 12. System.out.println(“The sum is “ + sum); 13. } 14. }

75 75 1. public class TestContinue { 2. public static void main(String[] args) { 3. int sum = 0, number = 0; 4. while (number < 5) { 5. number++; 6. if (number % 2 == 0) 7. continue; 8. sum += number; 9. } 10. System.out.println(“The number is “ + 11. number); 12. System.out.println(“The sum is “ + sum); 13. } 14. }

76 76 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): Converting for to while for Special Cases Example (based on Review Question 4.12, pg. 146): 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); } 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; i++; } System.out.println(sum); } Converted Correct Conversion (1) (2) Output for (1) and (2) is 3

77 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 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 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 AmountCommission Rate $0.01–$5,0008 percent $5,000.01–$10,00010 percent $10,000.01 and above12 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 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 >= 10000.01) commission = 5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12; else if (salesAmount >= 5000.01) commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10; else commission = salesAmount * 0.08; } while (commission < COMMISSION_SOUGHT); // Display the sales amount String output = "The sales amount $" + (int)(salesAmount * 100) / 100.0 + "\nis needed to make a commission of $" + COMMISSION_SOUGHT; JOptionPane.showMessageDialog(null, output); }

81 81 Exercise Write an algorithm and 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 -999. Use the while loop. An output example:

82 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; System.out.print("Enter a positive integer: "); number=scan.nextInt(); } System.out.println("Number of integers = " + counter); System.out.println("Biggest integer = " + biggest); System.out.println("Smallest integer = " + smallest); }

83 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 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); }


Download ppt "Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-61 Chapter 5 Control Statements."

Similar presentations


Ads by Google