






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







CMPU-101: Problem-Solving and Abstraction Marc Smith Vassar College Spring 2007 2 Up to now, we've been writing straight-line code: all program statements have been executed. Now we'll examine conditional execution if and if/else multiway branching 3
Circle c1 = new Circle(1.0); System.out.println(c1); Circle c2 = new Circle(-1.0); System.out.println(c2); 4 Prog1101 — Naïve Code for Circle public Circle ( double radius ) { this.radius = radius; } public double area() { return Math.PI * radius * radius; } public double circumference() { return 2.0 * Math.PI * radius; } G:>java Prog Circle: Radius: 1. Circumference: 6. Area: 3. Circle: Radius: -1. Circumference: -6. Area: 3.
public String toString() { return "\nCircle:\n" + String.format(" Radius: %6.2f\n", radius) + String.format(" Circumference: %6.2f\n", circumference()) + String.format(" Area: %6.2f\n", area()); }
7
A Circle can't have a negative radius. Catch this in the constructor — validation. Prog1102 — throw an Error if the radius is negative 8
public Circle ( double radius ) { if ( radius < 0.0 ) { throw new Error("Illegal radius: " + radius); } this.radius = radius; } 9
Involves a condition — a boolean expression. Uses the condition to "guard" a statement. The statement is only executed if the condition evaluates to true. 10
condition? statement false true
if ( … ) { statement } if ( … ) statement if ( … ) statement Don’t use these forms
Prog If a Circle is to have a negative radius, use 1.0 as the radius and notify the user of the change.
19
if ( loThreshold <= hiThreshold ) { this.loThreshold = loThreshold; this.hiThreshold = hiThreshold; } if ( loThreshold > hiThreshold ) { // Print appropriate message to System.out this.loThreshold = hiThreshold; this.hiThreshold = loThreshold; }
20
if ( c == 'a' ) return 'A'; if ( c == 'b' ) return 'B'; ... if ( c == 'z' ) return 'Z'; 21
if ('a' <= c && c <= 'z') return (char)(c + 'A' - 'a'); Note: ‘A’ - ‘a’ is -32 in Unicode table (p. 921) So subtracting 32 from a lower case char, c, results in the Unicode value corresponding to the upper case version of c Finally, we must cast the Unicode value back to a character 22
class Employee { private String name; private double rate; //----------------------------------------------------------------------- public Employee ( String name, double rate ) { this.name = name; this.rate = rate; } //-----------------------------------------------------------------------
public double calcPay ( int hours ) { if ( hours <= 40 ) { return this.rate * hours; } return this.rate * 40 + this.rate * 1.5 * ( hours - 40 ); }
System.out.print("\nEnter hourly rate: "); double rate = kb.nextDouble(); Employee e = new Employee("sam",rate); while ( true ) { System.out.print("\nHow many hours this week? "); int hours = kb.nextInt(); System.out.printf("\nPay is %6.2f\n",e.calcPay(hours)); } We’ll talk about while loops soon…
25
private static int abs ( int n ) { if ( n >= 0 ) return n; if ( n < 0 ) return -n; } //attempting to compile in DrJava: 1 error found: File: /Users/mlsmith/Desktop/cs 101 /Prog 1111 .java [line: 13 ] Error: missing return statement //Note the poor coding style! 26
if ( n% 2 == 0 ) System.out.println("even"); if ( n% 2 != 0 ) System.out.println("odd"); Why compute n% 2 twice? if ( n% 2 == 0 ) { System.out.println("even"); } else <------------------------- how convenient!!! { System.out.println("odd"); } //Note the poor coding style! 27
if ( cond ) { stmt } else { stmt } if ( cond ) stmt else stmt if ( cond ) stmt1 else stmt //Don’t do this - poor style 28
if ( loThreshold <= hiThreshold ) { various 1 } if ( loThreshold > hiThreshold ) { various 2 } if ( loThreshold <= hiThreshold ) { various 1 } else { various 2 }
if ( n >= 90 ) { letter = 'A'; } else if ( n >= 80 ) { letter = 'B'; } else if ( n >= 70 ) { letter = 'C'; } else if ( n >= 60 ) { letter = 'D'; } else { letter = 'F'; } Note: Many experienced programmers will place the ‘{‘ at the end of the ‘if’ line, instead bringing it down to the beginning of the next line. You may adopt this style if you like…we used it here in the interest of saving space
if ( n >= 90 ) { letter = 'A'; } if (( n >= 80 ) && ( n < 90 )) { letter = 'B'; } if (( n >= 70 ) && ( n < 80 )) { letter = 'C'; } if (( n >= 60 ) && ( n < 70 )) { letter = 'D'; } if ( n < 60 ) { letter = 'F'; } If A cutoff changes from 90 to 89 , we need to change the code in two places. Whenever you have to change something in multiple places, you run the risk of overlooking one of the change places.
37
if ( c == 'A' ) return true; ... if ( c == 'Z' ) return true; return false; 38
return 'A' <= c && c <= 'Z'; 39
return -1 != "ABCDEFGHIJKLMNOPQRSTUVWXYZ" .indexOf(c); 40
s 1? s 2? s 2? d 1 d 2 d 3 d 4 F F T F T T
if ( c 1 ) if ( c 2 ) a 1 ; else a 2 ; resolves as if ( c 1 ) { if ( c2 ) a 1 ; else a 2 ; } rather than if ( c 1 ) { if ( c2 ) a 1 ; } else a 2 ; An else belongs to the closest if which doesn't already have an else. Avoiding this confusion is one major reason for always using {}’s
43
private static int mystery ( int m, int n ) { if ( m < 0 ) if ( n < 5 ) return 1; else if ( n > 6 ) return 2; else return 3; else if ( n > 8 ) if ( m > 12 ) return 4; else return 5; else if ( m > 20 ) return 6; else return 7; } 44
if ( cond ) return expn1 ; else return expn2 ; should be if ( cond ) return expn1 ; return expn2 ; Better Form 45
Instead of writing this: write this: if ( cond == true ) if ( cond ) if ( cond == false ) if (! cond ) Instead of writing this: write this: if ( s 1 .equals(s 2 ) == true ) if ( s 1 .equals(s 2 ) ) if ( s 1 .equals(s 2 ) == false ) if ( !s 1 .equals(s 2 ) ) 46
Instead of writing this: write this: boolean b = ( cond == true ); boolean b = cond ; boolean b = ( cond == false ); boolean b =! cond ;
Instead of writing this: write this: if ( cond ) return true; else return false; return^ cond ; if ( cond ) return false; else return true; return^! cond ;
public static boolean even ( int n ) { return 0 == n%2; } public static boolean even ( int n ) { if (0 == n%2) return true; return false; }
55
class BinaryPanelListener implements ItemListener { //------------------------------------------------------------------------------ public void itemStateChanged ( ItemEvent event ) { total = 0 ; if ( b 4 .isSelected() ) total += 4 ; if ( b 2 .isSelected() ) total += 2 ; if ( b 1 .isSelected() ) total += 1 ; number.setText(total+""); } //------------------------------------------------------------------------------ } // end BinaryPanelListener 56
BinaryPanelListener bpl = new BinaryPanelListener(); b4.addItemListener(bpl); b2.addItemListener(bpl); b1.addItemListener(bpl); 57
58
private Image image, imageBacon, imageSammy; private JRadioButton bacon, sammy;
imageBacon = new ImageIcon("bacon.jpg").getImage(); imageSammy = new ImageIcon("sammy.jpg").getImage(); image = imageBacon; Define the Buttons & the ButtonGroup bacon = new JRadioButton("bacon",true); sammy = new JRadioButton("sammy"); ButtonGroup group = new ButtonGroup(); group.add(bacon); group.add(sammy);
RadioListener listener = new RadioListener(); bacon.addActionListener(listener);
class RadioListener implements ActionListener { //----------------------------------------------------------------------------- public void actionPerformed ( ActionEvent event ) { Object source = event.getSource(); if ( source == bacon ) image = imageBacon; else image = imageSammy; repaint(); } //----------------------------------------------------------------------------- } // end class RadioListener