1 / 47

Chapter 5– Making Decisions

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)…

tannar
Download Presentation

Chapter 5– Making Decisions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5– Making Decisions Dr. Jim Burns

  2. In Java, the simplest statement.. • Is the if(..) statement • if(someVariable==10) System.out.println(“The value of someVariable is 10”);

  3. 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

  4. 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

  5. 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

  6. The Result of every if(…) • Every if(..) produced a Boolean result…either true or false

  7. 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

  8. 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”);

  9. Nested IF’s If(itemsSold > 3) if(totalValue > 1000) bonus = 50; else bonus = 25; else bonus = 10;

  10. Using Multiple statements in an if or if…else structure Must use braces to designate blocks

  11. 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); }

  12. 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); } • }

  13. if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; }

  14. 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?”

  15. Observe the use of else If(itemsSold > 3) if(totalValue > 1000) bonus = 50; else bonus = 25; else bonus = 10;

  16. 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;

  17. The code above works like… Bonus = 0; If(itemsSold > 3) if(totalValue > 1000) bonus = 50;

  18. 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 &&

  19. 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;

  20. 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

  21. 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

  22. 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

  23. Incorrect range check code If(saleAmount >= 1000) commissionRate = .08; If(saleAmount >= 500) commissionRate = .06; If(saleAmount <= 499) commissionRate = .05;

  24. 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;

  25. 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?

  26. ANDing two Boolean expressions together

  27. Both of the Boolean expressions have to be true in order for the result of ANDing them to return a value of true

  28. ORing two Boolean expressions together

  29. 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

  30. 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..

  31. 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”); }

  32. 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”); }

  33. 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”);

  34. 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

  35. 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?

  36. int department; String supervisor; // Statement to get department value Switch (department) { case 1: case 2: case 3: supervisor = “Jones”; Break; case 4: supervisor = “Staples”;

  37. break; case 5; supervisor = “Tejano”; break; default: System.out.println(“Invalid department code”); }

  38. Using the conditional AND NOT Operators

  39. 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

  40. 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;

  41. Understanding precedence

  42. Precedence • Order of precedence agrees with common algebraic practice • Notice that the and && operator is always evaluated before the or || operator

  43. 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

  44. 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

  45. 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 =

  46. 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); } }

More Related