30 likes | 128 Views
Flow Of Control – Branching Statements. 5-1 If & If-Else Statements: If Statements branch if a boolean check is true: if(emp.hrs( ) > 40) emp.overTime ( ); // branch here if true emp.printCheck ( ); // Come here regardless If-Else Statements branch for either a true or false outcome:
E N D
Flow Of Control – Branching Statements • 5-1 If & If-Else Statements: • If Statements branch if a boolean check is true: • if(emp.hrs( ) > 40) emp.overTime( ); // branch here if true emp.printCheck( ); // Come here regardless • If-Else Statements branch for either a true or false outcome: • if(amt > acct.getBal( )) System.out.println(“Insufficient Funds”); else acct.with(amt); • Consider the flow charts on p183. • Multiple statements needs a begin and an end. • if(student.getAve( ) < 85) { student.getHelp( ); student.noticeHome( ); } else : • Indentation & Tabs p186 • Selection Operator p187 assign_boolCondition ? true : false y = (x > = 0) ? x : –x ;
5-2 Relational Operators : >, >=, <, <=, !=, = = != // Not Equal To = = // Check for equality. Why not = ? • What’s the difference between: a = 5; a = 3; if(a = = 5) if(a = 5) • Comparing Strings – Remember that Strings are Object references: String s1 = “Hi”; String s2 = “Hi”; if(s1= = s2) // T : But should not be used. Theory vs Reality (p190) if(s1.equals(s2)) // Is what you want to use! Overridden from Object! • Comparing Objects: The = = operator tests whether two Object references are identical (same address). Use the .equals( ) to compare objects. You will need to write your own equals( ) method for every ADT you write. • Useful String methods: • if(s1.equalsIgnoreCase(s2)) • if(s1.compareTo(s2) < 0) // alphabetical comparison // s1.compareTo(s2) returns -1, 0, or 1 • Comparing Floating-Point Numbers (5.2.2 p188-189) • When comparing floating-point numbers, test whether or not they are close enough! final double EPSILON = 1E-14; if(Math.abs(x – y) <= EPSILON) // x is approximately equal to y!
Consider an Updated car class: public class Car { private String make; //.getMake( ) returns make private String model; //.getModel( ) returns model private String vinNum; //.getVin( ) returns vinNum private int year; //.getYear( ) returns year // Write the following equals method comparing 2 Car Objects: // // if(car1.equals(car2)) public boolean equals(Car c) // step1 { if(make.equals(c.getmake( ))) //step2 if(model.equals(c.getModel( ))) if(vinNum.equals(c.getVin( ))) if(year = = c.getYear( )) return true; //step3 return false; } • Testing for null if(objVar = = null) //tests whether an Object reference exists String input = JOptionPane.showInputDialog(“Enter Number”); if(input = = null) //user canceled dialog box <eof>