470 likes | 572 Views
Chapter 5– Making Decisions. Dr. Jim Burns. In Java, the simplest statement. Is the if(..) statement if( someVariable ==10) System.out.println (“The value of someVariable is 10”);. if( someVariable ==10)…
E N D
Chapter 5– Making Decisions Dr. Jim Burns
In Java, the simplest statement.. • Is the if(..) statement • if(someVariable==10) System.out.println(“The value of someVariable is 10”);
if(someVariable==10)… • The if(…) statement evaluates to true when the value of someVariable is 10 and to false when the value of someVariable is not 10 • The System.out.println(..) only executes when the if(..) evaluates to true
In if(..) statements the Boolean expression must appear within parentheses • The statement ends after the action to be taken if the Boolean expression is true is declared • Then the semicolon appears
Irregardless of whether the Boolean expression is true or false, execution will continue with the next statement • The System.out.println() statement executes only if the statement is true
The Result of every if(…) • Every if(..) produced a Boolean result…either true or false
Single-alternative if(..) • if(someVariable==10) System.out.println(“The value of someVariable is 10”); • Only one action is performed based on the result of the Boolean expression
Dual-alternative if(..) Requires the use of the else keyword if(someVariable==10) System.out.println(“The value of someVariable is 10”); else System.out.println(“No, it’s not”);
Nested IF’s If(itemsSold > 3) if(totalValue > 1000) bonus = 50; else bonus = 25; else bonus = 10;
Using Multiple statements in an if or if…else structure Must use braces to designate blocks
If(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked – 40) * 1.5 * rate System.out.println(“Regular pay is “ + regularPay); System.out.println(“Overtime pay is “ + overtimePay); }
import javax.swing.JOptionPane; public class Payroll { public static void main(String[] args) { String hoursString; double rate = 20.00; double hoursWorked; double regularPay; double overtimePay; hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?"); hoursWorked = Double.parseDouble(hoursString); if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); System.exit(0); } • }
if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; }
if(…) cannot ask .. • “What number did the user enter?” • INSTEAD… • “Did the user enter a 1?” • “Did the user enter a 2?” • “Did the user enter a 3?”
Observe the use of else If(itemsSold > 3) if(totalValue > 1000) bonus = 50; else bonus = 25; else bonus = 10;
Using logical AND and OR statements • Rather than nested if’s, can AND two or more Boolean expressions together • The result is true only if all Boolean expressions are true Bonus = 0; If(itemsSold > 3 && totalValue > 1000) bonus = 50;
The code above works like… Bonus = 0; If(itemsSold > 3) if(totalValue > 1000) bonus = 50;
So why use the && operator?? • It makes your code more concise, less error-prone, and easier to understand • Note that when you use the && operator, you must include a complete Boolean expression on each side of the &&
bonus = 0; If(itemsSold > 100) bonus = 200; else if(totalValue > 3000) bonus = 200; Accomplishes the same as….. bonus = 0; If(itemsSold > 100 || totalValue > 3000) bonus = 200;
Using the assignment operator instead of the comparison operator when testing for equality Inserting a semicolon after the Boolean expression in an if statement Failing to block a set of statements with curly braces when several statements depend on the if or the else statement Avoiding Common errors when making decisions
Still more common errors… • Failing to include a complete Boolean expression on each side of an && or || operator in an if statement • Performing a range check incorrectly or inefficiently • Using the wrong operator with AND and OR
A range check is a series of if statements that determine whether a value falls within a specified range Performing accurate and efficient range checks
Incorrect range check code If(saleAmount >= 1000) commissionRate = .08; If(saleAmount >= 500) commissionRate = .06; If(saleAmount <= 499) commissionRate = .05;
Correct range check code…but inefficient If(saleAmount >= 1000) commissionRate = .08; else if(saleAmount >= 500) commissionRate = .06; else if(saleAmount <= 499) commissionRate = 0.05; . . else commissionRate = 0.05;
Using AND and OR appropriately • The boss might say “Print an error message when an employee’s hourly rate is under $5.65 and when an employee’s hourly pay rate is over $60” • If(payRate < 5.65 && payRate > 60) System.out.println(“Error in pay rate”); • What is wrong with this and how do you fix the problem?
Both of the Boolean expressions have to be true in order for the result of ANDing them to return a value of true
When ORing, if either Boolean expression is true, the result of ORing is true. • It’s only when both of the Boolean expressions are false that the result of ORing is false
Using the switch statement if(year == 1) System.out.println(“Freshman”); else if(year == 2) System.out.println(“Sophmore”); else if(year == 3) System.out.println(“Junior”); else if(year == 4) System.out.println(“Senior”); else System.out.println(“Invalid year”); Instead use the switch statement..
Int year; //get year value from user input or database Switch(year) { case 1: System.out.println(“Freshman”); break; case 2: System.out.println(“Sophomore”); break; case 3: System.out.println(“Junior”); break; case 4: System.out.println(“Senior”); break; default: System.out.println(“Invalid year”); }
Int year; //get year value from user input or database Switch(year) { case 1: System.out.println(“Freshman”); case 2: System.out.println(“Sophomore”); case 3: System.out.println(“Junior”); case 4: System.out.println(“Senior”); default: System.out.println(“Invalid year”); }
Int year; //get year value from user input or database Switch(year) { case 1: System.out.println(“Freshman”); Break; case 2: System.out.println(“Sophomore”); Break; case 3: System.out.println(“Junior”); Break; case 4: System.out.println(“Senior”); Break; default: System.out.println(“Invalid year”);
In the code above…. • The switch structure begins by evaluating the year variable in the switch statement • If year is equal to the first case value, which is one, “Freshman” is printed • The break statements bypass the rest of the switch structure and execution continues with the statement following the closing curly brace of the switch structure
switch() • What is the data type of the argument of a switch() statement? • Int, char, short and byte • Does a semicolon follow a switch statement? • What delimiter follows each case statement? • Are the break statements necessary for the code to work right?
int department; String supervisor; // Statement to get department value Switch (department) { case 1: case 2: case 3: supervisor = “Jones”; Break; case 4: supervisor = “Staples”;
break; case 5; supervisor = “Tejano”; break; default: System.out.println(“Invalid department code”); }
Consider the following code… If(a < b) smallerNum = a; else smallerNum = b; smallerNum = (a < b) ? A : b; The conditional operator uses the ? and the : to separate three expressions; the first expression must be a Boolean expression
Using the NOT Operator • You use the NOT operator which is written as the exclamation point (!), to negate the result of any Boolean expression If (age <= 25) premium = 200; else premium = 125; If(!(age <= 25)) premium = 125; else premium = 200;
Precedence • Order of precedence agrees with common algebraic practice • Notice that the and && operator is always evaluated before the or || operator
Example • Consider an auto insurance sys that determines the amount of premium to charge • Additional premium is charged to a driver who meets both of the following criteria: • Has more than two traffic tickets or is under 25 years old • Is male • Consider a 30 year old female driver with three traffic tickets
Code implementations // assigns extra premiums incorrectly if(trafficTickets > 2 || age < 25 && gender == ‘M’) extraPremium = 200; // assigns extra premiums correctly If((trafficTickets > 2 || age < 25) && gender == ‘M’) extraPremium = 200; Remember, do what is inside () first
import javax.swing.JOptionPane; public class Payroll { public static void main(String[] args) { String hoursString; double rate = 20.00; double hoursWorked; double regularPay; double overtimePay; hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?"); hoursWorked =
Double.parseDouble(hoursString); if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); System.exit(0); } }