Department of Computer and Information Science, School of Science, IUPUI Program Control using Java - Selection Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Dale Roberts 4.4 Control Structures (Cont.) Selection Statements if statement Single-selection statement if…else statement Double-selection statement switch statement Multiple-selection statement 2 Dale Roberts 4.5 if Single-Selection Statement if statements Execute an action if the specified condition is true Can be represented by a decision symbol (diamond) in a UML activity diagram Transition arrows out of a decision symbol have guard conditions Workflow follows the transition arrow whose guard condition is true 3 Dale Roberts Fig. 4.2 4 | if single-selection statement UML activity diagram. Dale Roberts 4.6 if…else Double-Selection Statement if…else statement Executes one action if the specified condition is true or a different action if the specified condition is false Conditional Operator ( ? : ) Java’s only ternary operator (takes three operands) ? : and its three operands form a conditional expression Entire conditional expression evaluates to the second operand if the first operand is true Entire conditional expression evaluates to the third operand if the first operand is false 5 Dale Roberts | …else double-selection statement UML activity diagram. Fig. 4.3 6 if Dale Roberts | multiple-selection statement UML activity diagram with statements. Fig. 5.11 switch break 7 Dale Roberts Software Engineering Observation 5.2 Provide a default case in switch statements. Including a default case focuses you on the need to process exceptional conditions. 8 Dale Roberts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // Fig. 5.9: GradeBook.java // GradeBook class uses switch statement to count A, B, C, D and F grades. import java.util.Scanner; // program uses class Scanner public class GradeBook { private String courseName; // name of course this GradeBook represents private int total; // sum of grades private int gradeCounter; // number of grades entered private int aCount; // count of A grades private int bCount; // count of B grades private int cCount; // count of C grades private int dCount; // count of D grades private int fCount; // count of F grades // constructor initializes courseName; // int instance variables are initialized to 0 by default public GradeBook( String name ) { courseName = name; // initializes courseName } // end constructor // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName Dale Roberts Outline GradeBook.j ava (1 of 5) Lines 8-14 9 29 // method to retrieve the course name 30 public String getCourseName() 31 { 32 33 return courseName; } // end method getCourseName 34 35 36 37 38 39 40 // display a welcome message to the GradeBook user public void displayMessage() { // getCourseName gets the name of the course System.out.printf( "Welcome to the grade book for\n%s!\n\n", getCourseName() ); GradeBook.j ava (2 of 5) 41 42 43 } // end method displayMessage Lines 50-54 44 45 public void inputGrades() { 46 47 48 49 50 51 52 53 54 Outline 10 // input arbitrary number of grades from user Scanner input = new Scanner( System.in ); Display prompt int grade; // grade entered by user System.out.printf( "%s\n%s\n %s\n %s\n", "Enter the integer grades in the range 0-100.", "Type the end-of-file indicator to terminate input:", "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter", "On Windows type <ctrl> z then press Enter" ); 55 Dale Roberts 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 // loop until user enters the end-of-file indicator while ( input.hasNext() ) { grade = input.nextInt(); // read grade total += grade; // add grade to total Loop condition uses method hasNext to ++gradeCounter; // increment numberdetermine of grades whether there is more data to input Outline // call method to increment appropriate counter incrementLetterGradeCounter( grade ); } // end while } // end method inputGrades // add 1 to appropriate counter for specified grade public void incrementLetterGradeCounter( int numericGrade ) { (grade / 10 ) is controlling // determine which grade was entered switch ( grade / 10 ) expression { case 9: // grade was between 90 switch statement determines which case 10: // and 100 case label to execute, depending on ++aCount; // increment aCount controlling expression break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch Dale Roberts 11 GradeBook.j ava (3 of 5) Line 57 Line 72 controlling expression Lines 72-94 case 7: // grade was between 70 and 79 83 Outline ++cCount; // increment cCount break; // exit switch 84 85 86 87 12 case 6: // grade was between 60 and 69 ++dCount; // increment dCount break; // exit switch 88 89 90 91 92 GradeBook.j ava (4 of 5) default: // grade was less than 60 ++fCount; // increment fCount break; // optional; will exit switch anyway 93 94 95 } // end switch default case for grade } // end method incrementLetterGradeCounter 96 97 98 // display a report based on the grades entered by user public void displayGradeReport() 99 { 100 101 102 System.out.println( "\nGrade Report:" ); 103 104 if ( gradeCounter != 0 ) { 105 106 less than 60 // if user entered at least one grade... // calculate average of all grades entered double average = (double) total / gradeCounter; 107 Dale Roberts Line 91 default case 108 // output summary of results 109 System.out.printf( "Total of the %d grades entered is %d\n", 110 gradeCounter, total ); 111 System.out.printf( "Class average is %.2f\n", average ); 112 System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", 113 "Number of students who received each grade:", 114 "A: ", aCount, // display number of A grades 115 "B: ", bCount, // display number of B grades 116 "C: ", cCount, // display number of C grades 117 "D: ", dCount, // display number of D grades 118 "F: ", fCount ); // display number of F grades 119 } // end if 120 else // no grades were entered, so output appropriate message 121 122 System.out.println( "No grades were entered" ); } // end method displayGradeReport 123 } // end class GradeBook Dale Roberts Outline 13 GradeBook.j ava (5 of 5) 1 // Fig. 5.10: GradeBookTest.java 2 3 4 // Create GradeBook object, input grades and display grade report. 5 { 6 7 8 Outline 14 public class GradeBookTest public static void main( String args[] ) { // create GradeBook object myGradeBook and Call GradeBook public methods to count grades 9 10 11 // pass course name to constructor GradeBook myGradeBook = new GradeBook( "CS101 Introduction to Java Programming" ); 12 13 14 myGradeBook.displayMessage(); // display welcome message myGradeBook.inputGrades(); // read grades from user 15 myGradeBook.displayGradeReport(); // display report based on grades 16 } // end main 17 } // end class GradeBookTest Dale Roberts GradeBookT est.java (1 of 2) Lines 13-15 Outline Welcome to the grade book for CS101 Introduction to Java Programming! 15 Enter the integer grades in the range 0-100. Type the end-of-file indicator to terminate input: On UNIX/Linux/Mac OS X type <ctrl> d then press Enter On Windows type <ctrl> z then press Enter 99 92 45 57 63 71 76 85 90 100 ^Z Grade Report: Total of the 10 grades entered is 778 Class average is 77.80 Number of students who received each grade: A: 4 B: 1 C: 2 D: 1 F: 2 Dale Roberts GradeBookT est.java (2 of 2) Program output Portability Tip 5.1 The keystroke combinations for entering end-of-file are system dependent. 16 Dale Roberts Good Programming Practice 5.8 Although each case and the default case in a switch can occur in any order, place the default case last. When the default case is listed last, the break for that case is not required. Some programmers include this break for clarity and symmetry with other cases. 17 Dale Roberts switch Multiple-Selection Statement (Cont.) Expression in each case Constant integral expression Combination of integer constants that evaluates to a constant integer value Character constant E.g., ‘A’, ‘7’ or ‘$’ Constant variable Declared with keyword final 18 Dale Roberts 5.7 break and continue Statements break/continue Alter flow of control break statement Causes immediate exit from control structure Used in while, for, do…while or switch statements continue statement Skips remaining statements in loop body Proceeds to next iteration Used in while, for or do…while statements 19 Dale Roberts Common Programming Error 5.7 Forgetting a break statement when one is needed in a switch is a logic error. 20 Dale Roberts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Fig. 5.12: BreakTest.java // break statement exiting a for statement. public class BreakTest { public static void main( String args[] ) Loop 10 times { int count; // control variable also used after Exitloop forterminates statement (break) when count equals 5 for ( count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, break; // terminate loop Outline 21 BreakTest.ja va Line 9 Lines 11-12 System.out.printf( "%d ", count ); } // end for System.out.printf( "\nBroke out of loop at count = %d\n", count ); } // end main } // end class BreakTest 1 2 3 4 Broke out of loop at count = 5 Dale Roberts Program output 1 // Fig. 5.13: ContinueTest.java 2 // continue statement terminating an iteration of a for statement. 3 4 5 public class ContinueTest { public static void main( String args[] ) 6 7 8 9 10 22 Loop 10 times { and proceed to for ( int count = 1; count <= 10; count++ ) //Skip loopline 10 12 times { line 7 when count equals 5 if ( count == 5 ) // if count is 5, continue; // skip remaining code in loop 11 12 13 14 Outline System.out.printf( "%d ", count ); } // end for 15 System.out.println( "\nUsed continue to skip printing 5" ); 16 } // end main 17 } // end class ContinueTest 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5 Dale Roberts ContinueTe st.java Line 7 Lines 9-10 Program output Software Engineering Observation 5.3 Some programmers feel that break and continue violate structured programming. Since the same effects are achievable with structured programming techniques, these programmers do not use break or continue. 23 Dale Roberts Software Engineering Observation 5.4 There is a tension between achieving quality software engineering and achieving the best-performing software. Often, one of these goals is achieved at the expense of the other. For all but the most performance-intensive situations, apply the following rule of thumb: First, make your code simple and correct; then make it fast and small, but only if necessary. 24 Dale Roberts Acknowledgements Deitel, Java How to Program Dale Roberts