Chapter 3 BỊ Decision Structures i Contents oi. The if Statement. The if-else Statement. The if-else-if Statement Nested if Statement Logical Operators.
Comparing String Objects More about Variable Declaration and Scope NO BRWN L Contents (Cont'd) oe 8. The Conditional Operators 9. The Switch Statement 10.Creating Objects with the DecimalFormat Class 11.The printf Method IL 1. The if Statement ~ = Problem: Write a program to calculate user’s average of 3 test scores.
If the average is greater than 95, the program congratulates the users on obtaining a high score. 5% lA 5 : xm 1 import javax.JOptionPane; 2 246 io 11 12 13 14 15 16 17 18 18 20 21 22 23 24 25 26 27 4 5 6 7 8 ae fur * This program demonstrates the if statement tự public class AverageScore { public static void main({String[] args) { double score1; // To hold score #1 double score2; // To hold score #2 double score3; // To hold score #3 double average; f/f To hold the average score String input; ff To hold the user's input //Get the first test score input = JOptionPane.showInputDialog("Enter score scorel = Double. parseDoublelinput); ¿/GEt the second test score input = JOptionPane.showInputDialog("Enter score score2 = Double. parseDoublelinput); //Get the third test score input = JOptionPane.showinputDialog("Enter score score3 = Double.
The if Statement (Cont'd) f//Calculate the average score average = (scorel + score2 + score3)/3; /fDisplay the average score JOptionPane.showMessageDialoginull, "The average is " + average); ff/If the score was greater than 95, let the user know ft if(average > 95) JOptionPane.showMessageDialoginull, "That's a great score!")j> System. The ¡£ Statement (Contd) ne = Simple decision structure logic Average > 95 Display “That's a great score!” false L 1. The if Statement (Cont'd) a= if (BooleanExpression) statement; The BooleanExpression must be a boolean expression « A boolean expression is either true or false If the BooleanExpression is true, the very next statement is executed. Otherwise, it is skipped.
The statement is conditionally executed because it only executes under the condition that the expression in the parentheses is true. Using Relational Operators to 7 Form Conditions Typically, the boolean expression is formed with a relational operator (binary operator. AN NV V A | HH II Greater Less than Greater than or equal to Less than or equal to Equal to Not equal to Using Relational Operators to 7 Form Conditions (Cont'd) oi = Assuming that a is 4, b iS 6, and c is 4 b>=a === true c<=a = true a>=5 == false c==6 === false b!=6 === false Programming Style and the if xi Statement = Two important style rules The conditionally executed statement should appear on the line after the i£ statement. The conditionally executed statement should be indented on level from the if statement.
if (value>32) ilu System.out<-printin(“Invalid number”) ; 11 “ts Be Careful with Semicolons No semicolon here 1f (BooleanExpression) Statement; Semicolon goes here int x = 0, y = 10; if (x > yY@) It will always System. “is greater than “ + y); 12 Multiple Conditionally 7 Executed Statements = Enclosing a group of statements by braces if(sales > 5000) These three statements bonus = 500.0; are executed commissionRate = 0.12; if sales is greater than dayOff += 1; 5000 13 [ Comparing Characters oe = Using the relational operators to test character data as well as number = Assuming ch iS a char variable: Compare ch to the character ‘A’: if (ch==‘A’) System.printin(“The letter is A.”); Compare the ch is not equal to ‘A’: 1f(ch!=)A' ) System.printin(“Not the letter is A. ‘A’ < ‘B’ —— true = In Unicode, the uppercase letters come before the lowercase letter. The if-else statement Problem Write a program to get two numbers and divide the first number by the second number.java ĐÓNG 3= ** 4 * 5 * This program demonstrates the if-else statements.
6 * 7 Tỷ B 3 public class Division 1ñ { 11 "12° public static void main(String[] args) 3 { double numberil, number2Z; f/f Division operands double quotient; f/ Result of division // Create a Scanner object for keyboard input Scanner keyboard = new Scanner (System.in); f/f Get the first number System.print("Enter a number: "j); numberil = keyboard.nextDouble[); Ỳ CC ñ 3 -¬1 em i + aL 24 // Get the second number 25 System.print("Enter another number: "j; 26 number2 = keyboard.nextDouble({); 25 if(number2 == QO} 29 { 30 System.printlin("Division by zero is not possible.printin("enter a number other than zero."); 33 } 34 else 35 { 36 quotient = nurmberl / number2; 37 system. The if-else statement oi Enter €@& number: 12 Enter another number: 5 [The quotient af 12.4 Enter & number: le Enter another number: LÍ bivision hy Zero if not possible. Please run the program again and enter €@ number other than fera. 19 Logic of the if-else 7 Statement false number2 true Ỳ — 3Í0) Ỳ Divide number1 by number2 Display the quotient Display error message 20 Logic of the if-else IL Statement (Cont'd) cl = The if-else statement will execute one group of statement if its boolean expression iS true, or another group if its boolean expression is false.
if (BooleanExpression) statement or block else Statement or block 21 3. The if-else-if [ Statement cL = Problem Write a program to ask the user to enter a numeric test score. Display a letter grade (A, B, C, D, or F) for the score. = score < 60 F » 60 <= score < 70 D „ 7/0 <= score < 80 C „ 80 <= score < 90 B =» 90 <= score <= 100 A » score > 100 Invalid score 22 Nel el l1 import jJavax.JOptionPane; 2 30 fre 4 * This program asks the user to enter a numeric test score and 5 * displays a letter grade for the score.
The program displays an 6 * error message if an invalid numeric score is entered. * 7 8 tự 9 public class TestResults 1ñ { 111= public static void main(String[] args) { int test5core; ¿#¿ Nuuœeric test score String input; ff To hold the user's input // Get the numeric test score input = JOptionPane.showInputDialog("Enter your numeric " + "test score and I will tell you the grade:"); testscore = Integer.showMessageDialoginull, "Your grade is F."); else if(testScore < 70) JOptionPane.showMessageDialoginull, "Your grade is D."); else if (testScore < 680) JOptionPane.showMessageDialoginull, "Your grade is C."); else if{testScore < 90) JOptionPane.showMessageDialoginull, "Your grade is B."); else if{testScore <= 100) JOptionPane.showMessageDialoginull, "Your grade is A.showMessageDialoginull, “Invalid score.ex2t(O); 24 "` Logic of the ¡ £- else-if Statement Display “Invalid score.” Display “Your grade is F.” Display “Your grade is D.” Display “Your grade is C.” Display “Your grade is A. The if-else-if 7 Statement » The if-else-if statement is a chain of if-else statements. Each statement in the chain performs its test until one of the tests is found to be true.
if (BooleanExpression) statement or block else if (BooleanExpression) statement or block ⁄⁄ //Put as many else if statement as needed here ⁄⁄ else statement or block 26 4. Nested ¡£ Statement a = Problem Write a Java program to determine whether a bank customer qualifies for a loan. To qualify, a customer must earn at least $30,000 per year, and must have been on his or her current job for at least two years. Nested if Statement no.
Input User’s annual salary Number of years at the current job false salary >= true 30000 v Display “You must earn at least $30,000 per year to qualify.” yearsOnJob >= 2 Display “You must have been on your Display “You qualify current job for at least 2 years to qualify.” for the loan.JOptionPane; f/f Needed for JOptionPane class 2 3=, ** 4 * This program demonstrates a nested if statement. 5 *f 6 public class LoanQualifier 7 4 ị 8© public static vwoid raain(Stringq[] args] 9 ( 10 double salary; // Annual salary 11 double yearsOnJob; // Years at current job 12 String input; // To hold string input 13 14 // Get the user's annual salary 15 input = JOptionPane.showInpurtDialog("Enter your " + 16 "annual salary. parseDourblelinput); 18 19 // Get the number of years at the current job 20 input = JOptionPane.showinputDialog("Enter the number of " + 21 "vears at your current job. parseDoublelinput); 29 a f/f Determine whether the user qualifies for the loan if (salary >= 30000) if (yearsOnJob >= 2) JOptionPane.showMessageDialogi(null,"You qualify " + "for the loan.showMessageDialoginull,"You must have " + "heen on your current job for at least " + "two years to qualify.showMessageDialog(null, "You must earn " + "at least $30000 per year to qualify.
Nested if Statement lạ (Contd) An if statement appears inside another if statement, it is considered nested. The rule for matching else clauses with if clauses is this: An else Clause goes with the closet previous if clause that doesn’t already have its own else Clause. 31 Alignment of ¡ £ and e1se [_clauses oe R2 ¿¿ Determine whether the user qualifies for the loan —p>ifisalary >= 30000) 26 if{yearsOnJob >= 2) 27 JOptionPane.showMessageDialog(null, "You qualify " + 28 "for the loan.showMessageDialoginull,"You must have " + 31 "heen on your current job for at least " + 32 "two years to qualify.showMessageDialog(null, "You must earn " + 35 "at least $30000 per year to qualify. Logical Operators mm = Logical operators connect two or more relational expressions into one or reverse the logic of an expression.
= Java provides two binary logical operators = && :AND = || :OR one unary logical operator a | : NOT 33 UT && Logical Operators (Contd) AND OR NOT Connects two boolean expression into one. Both expressions must be true for the overall expression to be true. Connects two boolean expression into one. One or both expressions must be true for the overall expression to be true.
It is only necessary for one to be true, and it does not matter which one. Reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator return true.
Logical Operators (Cont'd) x > y &&a<b Is x greater than y AND is a less than b? x == y || x == z_ Is x equal to y OR is x equal to z? !(x > y) Is the expression x > y NOT true? 35 [ The && Operator oi true true true true false false false true false false false false = The «& performs short-circuit evaluation If the expression on the left side of the «« operator is false, the expression on the right side will not be checked. NI The && Operator (Contd) oi = A different version of the LoanQualifier program salary >= 30000 && yearOnJob >= 2 Display “You do not Display “You qualify qualify for the loan.” for the loan.” 37 ¿# Determine whether the user qualifies for the loan if(salary >= 30000 ¢€& yearsOnJob >= 2) JOptionPane.showMessageDialoginull,"You qualify " + "for the loan.showMessageDialoginull,"You do not " + "qualify for the loan. ex2t¢(0); 38 The || Operator oi true true true true false true false true true false false false = The | | performs short-circuit evaluation If the expression on the left side of the | | operator is true, the expression on the right side will not be checked. 39 The || Operator a = Problem Write a Java program to determine whether a bank customer qualifies for a loan.
To qualify, a customer must earn at least $30,000 per year, OR must have been on his or her current job for at least two years. 40 7 The || Operator (Cont'd) | = Input User’s annual salary Number of years at the|current job yearsOnJob >= 2 Display “You qualify for the loan.” Display “You do not Display “You qualify qualify for the loan.” for the loan.