Chapter 3 Selections 20211022 Introduction to Java Programming

  • Slides: 37
Download presentation
Chapter 3 Selections 2021/10/22 Introduction to Java Programming Chapter 3 - 1

Chapter 3 Selections 2021/10/22 Introduction to Java Programming Chapter 3 - 1

3. 1 Introduction In this chapter, you will learn the following concepts: To declare

3. 1 Introduction In this chapter, you will learn the following concepts: To declare boolean type and write boolean expression. To distinguish between conditional and unconditional && and || operator. To use boolean expressions to control selection statements. To implement selection control using if and nested if statements. To implement selection control using switch statement. To write expressions using the conditional operator. To display formatted output … 2021/10/22 Introduction to Java Programming 2

3. 2 boolean Data Type and Operations Often in a program you need to

3. 2 boolean Data Type and Operations Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false. boolean b = (1 > 2); 2021/10/22 Introduction to Java Programming 3

Comparison Operators Operator Name < less than <= less than or equal to >

Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to 2021/10/22 Introduction to Java Programming 4

3. 3 Problem: A Simple Math Learning Tool This example creates a program to

3. 3 Problem: A Simple Math Learning Tool This example creates a program to let a first grader practice additions. The program randomly generates two single-digit integers number 1 and number 2 and displays a question such as “What is 7 + 9? ” to the student. After the student types the answer, the program displays a message to indicate whether the answer is true or false. 2021/10/22 Introduction to Java Programming 5

3. 4 If Statements 3. 4. 1 Simple if Statements (One-Way) 3. 6 if

3. 4 If Statements 3. 4. 1 Simple if Statements (One-Way) 3. 6 if … else Statements (Two-Way) 3. 7 Nested if statement 2021/10/22 Introduction to Java Programming 6

3. 4. 1 One-Way if Statements if (boolean. Expression) { statement(s); } 2021/10/22 if

3. 4. 1 One-Way if Statements if (boolean. Expression) { statement(s); } 2021/10/22 if (radius >= 0) { area = radius * PI; System. out. println("The area" “ for the circle of radius " + "radius is " + area); } Introduction to Java Programming 7

3. 5 Problem: Guessing Birthdays 2021/10/22 Introduction to Java Programming 8

3. 5 Problem: Guessing Birthdays 2021/10/22 Introduction to Java Programming 8

3. 6 Two-Way if Statement if (boolean. Expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case;

3. 6 Two-Way if Statement if (boolean. Expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } 2021/10/22 Introduction to Java Programming 9

if. . . else Example if (radius >= 0) { area = radius *

if. . . else Example if (radius >= 0) { area = radius * 3. 14159; System. out. println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System. out. println("Negative input"); } 2021/10/22 Introduction to Java Programming 10

3. 7 Nested if Statements if (i > k) { if ( j >

3. 7 Nested if Statements 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. ”); } 2021/10/22 Introduction to Java Programming 11

Multiple Alternative if Statements 2021/10/22 Introduction to Java Programming 12

Multiple Alternative if Statements 2021/10/22 Introduction to Java Programming 12

Trace if-else statement Suppose score is 70. 0 The condition is false if (score

Trace if-else statement Suppose score is 70. 0 The condition is false if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; 2021/10/22 Introduction to Java Programming 13

Trace if-else statement Suppose score is 70. 0 The condition is false if (score

Trace if-else statement Suppose score is 70. 0 The condition is false if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; 2021/10/22 Introduction to Java Programming 14

Trace if-else statement Suppose score is 70. 0 The condition is true if (score

Trace if-else statement Suppose score is 70. 0 The condition is true if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; 2021/10/22 Introduction to Java Programming 15

Trace if-else statement Suppose score is 70. 0 grade is C if (score >=

Trace if-else statement Suppose score is 70. 0 grade is C if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; 2021/10/22 Introduction to Java Programming 16

Trace if-else statement Suppose score is 70. 0 Exit the if statement if (score

Trace if-else statement Suppose score is 70. 0 Exit the if statement if (score >= 90. 0) grade = 'A'; else if (score >= 80. 0) grade = 'B'; else if (score >= 70. 0) grade = 'C'; else if (score >= 60. 0) grade = 'D'; else grade = 'F'; 2021/10/22 Introduction to Java Programming 17

3. 8 Common Errors in Selection Statements Forgetting Necessary Braces Dangling else Ambiguity Wrong

3. 8 Common Errors in Selection Statements Forgetting Necessary Braces Dangling else Ambiguity Wrong Semicolon at the if Line Redundant Testing of Boolean Values 2021/10/22 Introduction to Java Programming 18

if (i > k) if ( j > k ) System. out. println(“ i

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. ”); Wrong Semicolon at the if Line if ( boolean. Expression ) ; Redundant Testing of Boolean Values if ( even == true ) { } 2021/10/22 Introduction to Java Programming 19

3. 9 Problem: An Improved Math Learning Tool This example creates a program to

3. 9 Problem: An Improved Math Learning Tool This example creates a program to teach a first grade child how to learn subtractions. The program randomly generates two single-digit integers number 1 and number 2 with number 1 > number 2 and displays a question such as “What is 9 – 2? ” to the student. 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. 2021/10/22 Introduction to Java Programming 20

3. 10 Problem: Body Mass Index (BMI) is a measure of health on weight.

3. 10 Problem: Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. The interpretation of BMI for people 16 years or older is as follows: 2021/10/22 BMI interpretation Below 16 Seriously underweight 16 -18 underweight 18 -24 Normal weight 24 -29 overweight 29 -35 Seriously overweight Above Gravely overweight Introduction to Java Programming 21

3. 11 Problem: Computing Taxes The US federal personal income tax is calculated based

3. 11 Problem: 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 2009 are shown in following table. 2021/10/22 Introduction to Java Programming 22

Table 3. 2 2009 U. S. Federal Tax Rates Marginal Tax rate Single Married

Table 3. 2 2009 U. S. Federal Tax Rates Marginal Tax rate Single Married filing jointly or qualified widow(er) 10% $0 -$8, 350 $0 -$16, 700 $0 -$8, 350 15% $8, 351$33, 950 $16, 701%67, 900 … 25% $33, 951%82, 250 28% … Married filing separately Head of household $0 -$11, 950 33% 35% 2021/10/22 Introduction to Java Programming 23

Example 3. 1 Computing Taxes, cont. if (status == 0) { // Compute tax

Example 3. 1 Computing Taxes, cont. 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 } Compute Tax. With. Selection. Statement 2021/10/22 Introduction to Java Programming 24

3. 12 Logical Operators Operator Name ! not && and || or ^ exclusive

3. 12 Logical Operators Operator Name ! not && and || or ^ exclusive or & and ( can also be apply to bitwise operations) | or ( can also be apply to bitwise operations) 2021/10/22 (Conditional AND) Short-circuit AND (Conditional OR) Short-circuit OR Introduction to Java Programming 25

3. 13 Problem: Determining Leap Year 2021/10/22 Introduction to Java Programming 26

3. 13 Problem: Determining Leap Year 2021/10/22 Introduction to Java Programming 26

3. 14 Problem: Lottery The program randomly generates a lottery of a twodigit number,

3. 14 Problem: Lottery The program randomly generates a lottery of a twodigit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule: If the user input matches the lottery in exact order, the award is $10, 000. If all the digits in the user input match all the digits in the lottery, the award is $3, 000. If one digit in the user input matches a digit in the lottery, the award is $1, 000. 2021/10/22 Introduction to Java Programming 27

3. 15 switch Statements switch (status) { case 0: compute taxes for single filers;

3. 15 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); } 2021/10/22 Introduction to Java Programming 28

switch Statement Flow Chart 2021/10/22 Introduction to Java Programming 29

switch Statement Flow Chart 2021/10/22 Introduction to Java Programming 29

The switch-expression must yield a value of char, byte, short, or int type and

The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses. The value 1, …, value. N must have the same data type as the value of the switch-expression. Note that value 1, …, value. N are constant expressions, meaning that they cannot contain variables in the expression, such as 1+x. When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. 2021/10/22 Introduction to Java Programming 30

The keyword break is optional. The default case, which is optional, can be used

The keyword break is optional. 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 checked in sequential order, but the order of the cases (including the default case) does not matter. 2021/10/22 Introduction to Java Programming 31

3. 16 Conditional Operator (boolean. Exp) ? exp 1 : exp 2 if (num

3. 16 Conditional Operator (boolean. Exp) ? exp 1 : exp 2 if (num % 2 == 0) System. out. println(num + “is even”); else System. out. println(num + “is odd”); System. out. println( (num % 2 == 0)? num + “is even” : num + “is odd”); 2021/10/22 Introduction to Java Programming 32

3. 17 Formatting Console Output and String Use the new JDK 1. 5 printf

3. 17 Formatting Console Output and String Use the new JDK 1. 5 printf statement. System. out. printf(format, item); Where format is a string that may consist of substrings and format specifiers. A format specifier specifies how an item should be displayed. An item may be a numeric value, character, boolean value, or a string. Each specifier begins with a percent sign. 2021/10/22 Introduction to Java Programming 33

Frequently-Used Specifiers Specifier Output Example %b a boolean value true or false %c a

Frequently-Used Specifiers Specifier Output Example %b a boolean value true or false %c a character 'a' %d a decimal integer 200 %f a floating-point number 45. 460000 %e a number in standard scientific notation 4. 556000 e+01 %s a string "Java is cool" Items must match the specifiers in order, in number, and in exact type. Specifying Width and Precision 2021/10/22 Introduction to Java Programming 34

3. 18 Operator Precedence and Associativity var++, var-+, - (Unary plus and minus), ++var,

3. 18 Operator Precedence and Associativity var++, var-+, - (Unary plus and minus), ++var, --var (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) 2021/10/22 Introduction to Java Programming 35

Operand Evaluation Order The left-hand operand of a binary operator is evaluated before any

Operand Evaluation Order The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. The rule of evaluating an expression is: Evaluate whatever subexpressions you can possibly evaluate from left to right; The operators are applied according to their precedence; The associativity rule applies for two operators next to each other with the same precedence. Example 3+4*4>5*(4+3)– 1 i-- + ( i * 3 ) 2021/10/22 Introduction to Java Programming 36

3. 19 (GUI) Confirmation Dialog int option = JOption. Pane. show. Confirm. Dialog(null, "Continue");

3. 19 (GUI) Confirmation Dialog int option = JOption. Pane. show. Confirm. Dialog(null, "Continue"); JOption. Pane. YES_OPTION; JOption. Pane. NO_OPTION; JOption. Pane. CANCEL_OPTION; 2021/10/22 Introduction to Java Programming 37