1 / 80

Implementing Decisions in Java: If Statements, Blocks, and Comparison Operators

This chapter explores how to implement decisions in Java using if statements, grouping statements into blocks, comparing different data types, and understanding the correct ordering of decisions in multiple branches.

alexj
Download Presentation

Implementing Decisions in Java: If Statements, Blocks, and Comparison Operators

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 6 - Decisions

  2. Chapter Goals • To be able to implement decisions using if statements • To understand how to group statements into blocks • To learn how to compare integers, floating-point numbers, strings, and objects • To recognize the correct ordering of decisions in multiple branches • To program conditions using boolean operators and variables

  3. Decisions • So far, our examples haven’t made any decisions • The same code gets executed no matter what • Assignment 1 • Path • BankAccount • This is called sequential execution • Is this how real applications work?

  4. Decisions • The real world requires decisions • Is it time to feed the cat? Can a book be checked out? • Essential feature of nontrivial programs is to make decisions based on input • The answers to these decision require different actions • Introduces the need for control statements

  5. If statements • Conditional statements are represented with if-then-else statements Scanner stdin = new Scanner(System.in); int testScore = stdin.nextInt(); if (testScore < 70) { System.out.println(“You are below the mean”); } else { System.out.println(“You are above the mean”); }

  6. If Statements: Syntax if (<boolean expression>) { <then block> } else { <else block> }

  7. Example • withdraw() method we implemented allowed user to withdraw as much money as they wanted • Is this realistic? • What decision should withdraw() make? • What should the decision be based on?

  8. Example public void withdraw(double amount){ if (amount <= balance) balance -= amount; }

  9. Example • Most banks also charge an overdraft penalty, how would we go about changing our example to implement this?

  10. Statements • The decision we made only resulted in one instruction whichever way we took • Most decisions lead to a sequence of instructions (multiple statements). • In order to show that the entire sequence of instructions belong to the then-block (or else-block), we group them with curly braces{ } • A sequence of instructions surrounded by curly braces is called a block

  11. Example if (amount <= balance) { System.out.println(“Legal Withdrawal”); balance = balance – amount; } else { balance = balance – OVERDRAFT_PENALTY; }

  12. Statements • Block statement – a group of statements enclosed within curly braces • Methods • Classes • if statements, switch statements, loops • Simple statement • Basic statement such as balance = balance – amount; • Compound statement • Statements that have multiple paths of execution • If statements, loops

  13. If Statements • If you have a single statement, { } not required if (testScore < 70) System.out.println(“You are below the mean”); else System.out.println(“You are above the mean”); • But convention to use them anyways • Helpful for adding temporary output to check if a branch is executed • Makes nested if-else statements easier to read

  14. If Statements: Syntax if(condition)statement if (condition)statement1 elsestatement2 statementmust be a statement - simple, compound, or block

  15. Style • Use indentation to indicate nesting levels public class BankAccount { | … | public void withdraw() | { | | if (amount <= balance) | | { | | | balance -= amount; | | } | } }

  16. Die Example // Declare and create Die objects Die die1 = new Die(); Die die2 = new Die(); // Roll die objects die1.roll(); die2.roll(); // Save results in new variables int roll1 = die1.getTop(); int roll2 = die2.getTop();

  17. Die Example // Test for doubles if ( roll1 == roll2 ) System.out.println( "Doubles" ); // rest of program

  18. Die Example roll1 == roll2 true System.out.println( “doubles!” ); false ... continue with rest of program

  19. Die Example // Test for doubles if ( roll1 == roll2 ) System.out.println( "Doubles" ); else System.out.println( "Sorry, no doubles" ); // rest of program

  20. Die Example roll1 == roll2 true System.out.println( “doubles!” ); false System.out.println( “sorry ...” ); ... continue with rest of program

  21. Selection Operator • Selection Operator condition ? value1 : value2 • If the condition is true, value1 is returned. • If the condition is false, value2 is returned. • Example: Absolute Value y = (x >= 0) ? x : -x;

  22. Booleans • boolean is a primitive data type that holds one of two values • true • false • Any time a decision needs to be made, we make that decision using a boolean expression, which evaluates to a boolean value • Note: a mathematical expression returns a numerical value

  23. Boolean Expressions • What operators are used for boolean expressions? < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to

  24. Boolean Expressions • Boolean expressions are just like mathematical expressions, but they return true or false (not int, double, etc) • Examples: • 3 * 8 <= 5 * 5 • 6 % 4 > 0 • testScore < 80 • testScore * 2 > 350

  25. If Statements • When the computer reaches an if statement, it first evaluates the boolean expression • If that expression is true, the <then block> is executed • Otherwise, the <else block> is executed • An if statement is called a branching statement because it branches to a block of code

  26. Comparisons • Comparing whole numbers is trivial int a = 5; if (a == 5){ System.out.println(“Wow this is easy!”); } else { System.out.println(“Java really sucks”); }

  27. Comparisons • Comparing real numbers is more difficult because we have to take into account roundoff errors. double r = Math.sqrt(2); double d = r * r – 2; if (d != 0){ System.out.println(“Your equation is incorrect, the result is “ + d); } Your equation is incorrect, the result is 4.440892098500626E-16

  28. Comparisons • This is a problem, since logically the equation makes sense • Lesson: Floating point numbers may not be exact • Solution: Use range of values that are close enough • Should be close to 0

  29. Comparisons • To avoid roundoff errors, don't use == or != to compare floating-point numbers • To compare floating-point numbers test whether they are close enough: |x - y| ≤ ε final double EPSILON = 1E-14;if (Math.abs(x - y) <= EPSILON)// x is approximately equal to y • ε is a small number such as 10-14

  30. Comparisons • We can do comparisons with characters as well • They work according to ASCII values: char choice = 'Q'; if (choice < 'Z') System.out.println("valid"); else System.out.println("invalid"); • What is the output?

  31. Side Note: Characters • Remember that we said a char is one letter, digit, or symbol that the computer thinks of as a number. • We can cast chars to int and vice versa • Examples: • (int) 'D' -> 68 • (char) 106 -> 'j' • (char) ('D' + 1) -> 'E'

  32. Comparisons • Boolean operators can be used on objects, but do they mean the same thing? • They probably don’t do what you expect… • Primitive types vs. reference types (objects) • To test two Strings, use equals() method

  33. String Comparisons • Don't use == for strings!if (input == "Y") // WRONG!!! • Use equals method:if (input.equals("Y")) string1.equals(string2); • == tests references, .equals() tests contents

  34. :String 0 1 2 3 4 R o b b y s1 s2 String Comparisons String s1 = "Robby", s2; s2 = s1;

  35. :String 0 1 2 3 4 R o b b y s1 s2 String Comparisons • What is the result of: s1 == s2 Why?

  36. :String 0 1 2 3 4 R o b b y s1 s2 String Comparisons String s1 = "Robby", s2; s2 = "Robby";

  37. :String 0 1 2 3 4 R o b b y str1 str2 String Comparisons • What is the result of: str1 == str2 Why?

  38. :String :String 0 1 2 3 4 0 1 2 3 4 R o b b y R o b b y s1 s2 String Comparisons String s1 = "Robby", s2; s2 = new String( s1 );

  39. :String :String 0 1 2 3 4 0 1 2 3 4 R R o o b b b b y y s1 s2 String Comparisons • What is the result of: s1 == s2 Why?

  40. :String :String 0 1 2 3 4 0 1 2 3 4 R R o o b b b b y y s1 s2 String Comparisons • What is the result of: s1.equals(s2); Why?

  41. String Comparisons • equalsIgnoreCase can be used to compare strings while ignoring case • Case insensitive test ("Y" or "y")if (input.equalsIgnoreCase("Y")) string1.equalsIgnoreCase(string2) // returns boolean • compareTo returns a number that tells which string comes before the other in the dictionary • 0 indicates that the strings are the same

  42. String Comparisons string1.compareTo(string2) • Returns < 0 if string1 comes first • Returns 0 if they are equal • Returns > 1 if string2 comes first • Example: "car" comes before "cargo" • All uppercase letters come before lowercase: "Hello" comes before "car"

  43. Comparisons • == tests for identity, equals() for identical content • Most classes have an equals() method defined Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); • box1 == box3is false • box1.equals(box3)is true • box1 == box2 is true • Note: equals() must be defined for the class for this to work

  44. Null • Reference variables store a reference (address) for an actual object • What do they store when they haven’t been set to refer to an object? • null is a Java reserved word to designate that no object has been set for that variable

  45. Null • Can be used in tests: if (middleInitial == null)System.out.println(firstName + " " + lastName); elseSystem.out.println(firstName + " " + middleInitial + ". " + lastName); • Use ==, not equals, to test for null • null is not the same as the empty string ""

  46. Multiple Alternatives if (score >= 90) System.out.println("Great!"); else if (score >= 80) System.out.println("Good"); else if (testScore >= 70) System.out.println("OK"); else if (testScore >= 60) System.out.println("Passing"); else if (testScore >= 50) System.out.println("Hmm..."); else if (testScore >= 0) System.out.println("Study!"); else System.out.println("Invalid Score");

  47. Multiple alternatives • First condition that is true is the ONLY statement executed • Therefore, order matters: if (testScore >= 90) System.out.println(“Great!”); else if (testScore >= 80) System.out.println(“Good”); else if (testScore >= 70) System.out.println(“OK”);

More Related