Docsity

Java Programming: Conditional Execution and Branching Statements - Prof. Marc L. Smith, Exams of Computer Science

Toggle sidebar
bg1
Chapter 11
Conditional Execution
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
Driver to Test Class Circle
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; }
5
G:\>java Prog1101
Circle:
Radius: 1.00
Circumference: 6.28
Area: 3.14
Circle:
Radius: -1.00
Circumference: -6.28
Area: 3.14
6
Output Uses String.format
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());
}
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Java Programming: Conditional Execution and Branching Statements - Prof. Marc L. Smith and more Exams Computer Science in PDF only on Docsity!

Chapter 11

Conditional Execution

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

Driver to Test Class Circle

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.

Output Uses String.format

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

Rejecting an Invalid Value

A Circle can't have a negative radius. Catch this in the constructor — validation. Prog1102 — throw an Error if the radius is negative 8

Prog 1102 — Constructor

public Circle ( double radius ) { if ( radius < 0.0 ) { throw new Error("Illegal radius: " + radius); } this.radius = radius; } 9

if

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

Flowchart of

if ( condition ) statement

condition? statement false true

Styles of if

if ( … ) { statement } if ( … ) statement if ( … ) statement Don’t use these forms

Correcting an Invalid Value

Prog If a Circle is to have a negative radius, use 1.0 as the radius and notify the user of the change.

19

Prog 1107 — Validate: (in constructor)

if ( loThreshold <= hiThreshold ) { this.loThreshold = loThreshold; this.hiThreshold = hiThreshold; } if ( loThreshold > hiThreshold ) { // Print appropriate message to System.out this.loThreshold = hiThreshold; this.hiThreshold = loThreshold; }

} //reverse given^ vals

20

public static char toUpperCase( char c )

if ( c == 'a' ) return 'A'; if ( c == 'b' ) return 'B'; ... if ( c == 'z' ) return 'Z'; 21

public static char toUpperCase( char c )

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

Prog 1110 — Computing Pay With Overtime

class Employee { private String name; private double rate; //----------------------------------------------------------------------- public Employee ( String name, double rate ) { this.name = name; this.rate = rate; } //-----------------------------------------------------------------------

Prog 1110

class Employee, calcPay() method:

public double calcPay ( int hours ) { if ( hours <= 40 ) { return this.rate * hours; } return this.rate * 40 + this.rate * 1.5 * ( hours - 40 ); }

Prog 1110 (main method)

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

Prog 1111 :

You Can't End a Non-void Method

With an if Statement

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

Introduction to if-else

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

Styles of if-else

if ( cond ) { stmt } else { stmt } if ( cond ) stmt else stmt if ( cond ) stmt1 else stmt //Don’t do this - poor style 28

Improving Temperature Classifier

if ( loThreshold <= hiThreshold ) { various 1 } if ( loThreshold > hiThreshold ) { various 2 } if ( loThreshold <= hiThreshold ) { various 1 } else { various 2 }

Multiway Branching —

The Letter Grade Problem

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

Danger, Will Robinson! Brittle Code!

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

public static boolean isUpperCase ( char c ) — 3

if ( c == 'A' ) return true; ... if ( c == 'Z' ) return true; return false; 38

public static boolean isUpperCase ( char c ) — 4

return 'A' <= c && c <= 'Z'; 39

public static boolean isUpperCase ( char c ) — 5

return -1 != "ABCDEFGHIJKLMNOPQRSTUVWXYZ" .indexOf(c); 40

In-Class Exercise:

2 Symptoms, 4 Diseases

s 1? s 2? s 2? d 1 d 2 d 3 d 4 F F T F T T

Nested if and Dangling else

if ( c 1 )

if ( c 2 ) a 1 ;

else a 2 ;

if ( c 1 )

if ( c 2 ) a 1 ;

else a 2 ;

To the compiler, these are all the same.

To which if does the else belong?

if ( c 1 ) if ( c 2 ) a 1 ; else a 2 ;

Resolving Dangling else

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

Nested ifs Can Be Hard to Understand

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

Style: return after else

if ( cond ) return expn1 ; else return expn2 ; should be if ( cond ) return expn1 ; return expn2 ; Better Form 45

Style: if ( cond == true )

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

Style

Instead of writing this: write this: boolean b = ( cond == true ); boolean b = cond ; boolean b = ( cond == false ); boolean b =! cond ;

More Style

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 )

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

BinaryPanelListener

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

Establish Listeners

BinaryPanelListener bpl = new BinaryPanelListener(); b4.addItemListener(bpl); b2.addItemListener(bpl); b1.addItemListener(bpl); 57

Prog 1116 — Radio Buttons

58

Instance Variables of MyPanel

private Image image, imageBacon, imageSammy; private JRadioButton bacon, sammy;

Set Up the Images

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

Establish the Listener

RadioListener listener = new RadioListener(); bacon.addActionListener(listener);

sammy.addActionListener(listener);

Here's the 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