principles of computer
play

Principles of Computer Implementing decisions using if statements - PDF document

Lecture Outline Principles of Computer Implementing decisions using if statements Science I Grouping statements into blocks Comparing numbers, strings, and objects Prof. Nadeem Abdul Hamid Using Boolean operators and variables


  1. Lecture Outline Principles of Computer  Implementing decisions using if statements Science I  Grouping statements into blocks  Comparing numbers, strings, and objects Prof. Nadeem Abdul Hamid  Using Boolean operators and variables CSC 120 – Fall 2005 Lecture Unit 6 - Decisions 1 2 CSC120 — Berry College — Fall 2005 Making Decisions if / else Statement  Does this work?  Computer programs often need to make decisions if ( amount <= balance )  Take different actions depending on some condition(s) balance = balance - amount;  Example: Can’t withdraw more money than in if ( amount > balance ) account balance balance = balance - OVERDRAFT_PENALTY;  “If amount-to-withdraw is less than available balance then deduct from balance; otherwise charge a penalty to the  How about this? balance.” if ( amount <= balance ) balance = balance - amount;  else if ( amount <= balance ) balance = balance - OVERDRAFT_PENALTY; balance = balance - amount; 3 4 Types of Statements Syntax: if Statement  Simple if ( condition ) statement balance = balance - amount;   Compound if ( condition ) statement1 else statement2 if ( amount <= balance ) balance = balance - amount;   Block Purpose: Purpose:  Groups multiple statements together To execute a statement(s) depending on whether  Can be used anywhere a single statement is used a condition is true or false { double newBalance = balance - amount; balance = newBalance; } 5 6 1

  2. Brace Layout Syntax: Block Statement  Doesn’t matter to compiler – matters to human {  Two suggested styles – choose one and stick to it statement1 statement2 ... if ( amount <= balance ) } { double newBalance = balance - amount; balance = newBalance; } Purpose: Purpose:  or To group several statements together to form a if ( amount <= balance ) { single statement double newBalance = balance - amount; balance = newBalance; } 7 8 Indentation public class BankAccount { . . . Comparing Values public void withdraw( double amt ) {  Another very critical way to if ( amt <= balance ) { make programs readable  Relational operators double newBal = balance - amt; for humans balance = newBal; } Java Math Notation Description  Use spaces instead of tab } . . . } > > Greater than key >= ≥ Greater than or equal  2, 3, or 4 spaces are best public class BankAccount { < < Less than  Tips . . . <= ≤ Less than or equal public void withdraw( double amt ) Always type the beginning and {  == = Equal if ( amt <= balance ) ending braces first, then fill in { between != ≠ Not equal double newBal = balance - amt; balance = newBal; Put comment after closing  } // end if  == operator denotes equality testing brace to indicate what it } // end withdraw method matches . . . } // end BankAccount class a = 5; // Assign 5 to a if ( a == 5 ) . . . // Test whether a equals 5 9 10 Comparing Floating Point Comparing Floating Point (Correctly)  Test whether (absolute value of) the double r = Math.sqrt( 2 ); difference between two number is close to 0 double d = r * r -2; if ( d == 0 )  Threshold often referred to as ε – ‘epsilon’ System.out.println( "sqrt(2)squared minus 2 is 0” ); else System.out.println( "sqrt(2)squared minus 2 is not 0 but " + d ); x � y � � sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16  In Java:  Don’t compare floating point numbers for (exact) equality == final double EPSILON = 1E-14;  Doesn’t work because of roundoff errors . . .  Instead, check if they are close enough (up to a if ( Math.abs(x - y) <= EPSILON ) // x is approximately equal to y desired threshold) 11 12 2

  3. Comparing Strings Comparing Order of Strings  Use the compareTo method  Don’t use == for strings either! s.compareTo(t) < 0 means s comes before t if (input == "Y") // WRONG!!!  s.compareTo(t) > 0 means s comes after t  Use the equals method  s.compareTo(t) == 0 means s and t are equal  if (input.equals("Y")) . . .  Java’s ‘dictionary’ order is according to Unicode  == tests identity; equals tests equal contents  ‘car’ comes before ‘cargo’  Will see this again in ‘Comparing Objects’ slides  All uppercase letters come before lowercase  ‘Hello’ comes before ‘car’  To test equality ignoring upper/lowercase (‘Y’ or ‘y’)  Numbers come before letters  ‘1’ comes before ‘a’ if (input.equalsIgnoreCase("Y")) . . .  See Appendix B in textbook 13 14 Comparing Objects Object References Rectangle box1 = new Rectangle(5, 10, 20, 30);  Like strings, == tests identity; equals tests contents Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30);  box1 != box3 but box1.equals( box3 )  box1 == box2  Warning: equals method must be defined properly by the class before you can use it 15 16 Testing for null Strings and null  Object variable may be set to null  Empty string is ""  Indicates ‘no object’  Valid string of length 0 String middleInitial = null; // Not set if ( . . . )  null indicates a string variable does not middleInitial = middleName.substring(0, 1); refer to anything, not even an empty string  Can be used as a condition (use == ): if (middleInitial == null) System.out.println(firstName + " " + lastName);  Always test for null using == not the equals else method System.out.println(firstName + " " + middleInitial + ". " + lastName); 17 18 3

  4. Conditions with Side Effects Multiple Alternatives  Sequences of comparisons  Avoid in if statements! if ( condition1 ) statement1 ;  Bad programming practice else if ( condition2 ) statement2 ;  Side effects: assignment, increment, decrement . . . else statementN ; Earthquake.java if ( ( d = b * b - 4 * a *c ) >= 0 ) r = Math.sqrt( d ); EarthquakeTester.java  The first matching condition is executed if ( n-- > 0 ) . . .  Order matters! if ( richter >= 0 ) // always passes r = "Generally not felt by people";  Can occasionally be useful to simplify loops else if ( richter >= 3.5 ) // not tested r = "Felt by many people, no destruction. . .  Next chapter 19 20 if vs. if/else Nested Branches  Consider carefully which one is appropriate to use  One if statement inside another if ( richter >= 8.0 ) if ( condition1 ) { r = "Most structures fall"; if ( condition1A ) if ( richter >= 7.0 ) statement1A ; r = "Many buildings destroyed"; if ( richter >= 6.0 ) else r = "Many buildings considerably damaged, some collapse"; statement1B ; if ( richter >= 4.5 ) } else r = "Damage to poorly constructed buildings"; statement2 ; if ( richter >= 3.5 ) r = "Felt by many people, no destruction"; if ( richter >= 0 ) r = "Generally not felt by people"; return r; 21 22 Example: Computing Taxes Taxes Flowchart If your filing status is single If your filing status is married Tax Bracket Percentage Tax Bracket Percentage $0 … $21,450 15% $0 … $35,800 15% Amount over $21,451, 28% Amount over 28% up to $51,900 $35,800, up to $86,500 Amount over $51,900 31% Amount over $86,500 31% 23 24 4

  5. Tax Program Preparing Test Cases  Test cases should achieve complete  TaxReturn.java coverage of input possibilities  TaxReturnTester.java  Tax program  2 filing possibilities  3 tax brackets  = 6 possible combinations  To test the program, select 6 valid inputs  Beware ‘Dangling else’: pg 210 and at least 1 invalid input (negative income) 25 26 Selection Operator switch Statement condition ? value1 : value2  Replaces sequence of if / else / else comparing single integer value against constant alternatives  Combines values to yield another value depending on condition int digit; switch ( digit ) { . . . case 1: System.out.print( "one" );  if construct combines statements if ( digit == 1 ) break; System.out.print( "one" ); case 2: System.out.print( "two" ); else if ( digit == 2 ) break; System.out.print( "two" ); case 3: System.out.print( "three" ); if ( x >= 0 ) y = x; else y = -x; else if ( digit == 3 ) break; System.out.print( "three" ); . . . y = x >= 0 ? x : -x; . . . case 9: System.out.print( "nine" ); else if ( digit == 9 ) break; System.out.print( "nine" ); default: System.out.print( "error" ); else break; System.out.print( "error" ); } 27 28 switch Statement (cont.) The boolean Type  Case values must be constants and must be  George Boole (1815-1864): pioneer in the integers, characters, or enumerated study of logic constants  Cannot be used with floating point, string, or  Value of an expression like amount < 100 is objects either true or false  Without break statements, execution ‘falls  boolean type: one of these two truth values through’ to the next case until the end  Sometimes referred to as 0 and 1 double amount = 0; boolean b = amount < 1000; System.out.println( b ); 29 30 5

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend