Workshop: Lab 5 Engineering Software 1 Lab 5: A deeper look at Control Statements Learning Objectives In this lab exercise you will learn: • The essentials of counter-controlled repetition. • To use the for and do…while repetition statements to execute statements in a program repeatedly. • To understand multiple selection using the switch selection statement. • To use the break and continue program control statements to alter the flow of control. • To use the logical operators to form complex conditional expressions in control statements. Lab Work General Note: Study every exercise and for each of them draw a structure diagram. Type in all these programs and run them inside your Java development kit. In your log-book take note of all the results from the execution of these programs and write down any problems that you had to solve. For each program of the exercises, explain clearly what each section of the program is doing. You may need to perform a walk-through, line by line, where this is appropriate. Record all your explanations in the log-book. Remember to put a date in your log-book and also to offer some discussions and a brief conclusion after every week’s work. Finally, complete the programming assignments at the end of the exercises, then enter comments in your logbook as you are doing this and save to your floppy disk/CD for submission with your logbook. Background • The for repetition statement specifies the details of counter-controlled-repetition. The general format of the for statement is for ( initialization; loopContinuationCondition; increment ) statement where the initialization expression names the loop’s control variable and provides its initial value, loopContinuationCondition is the condition that determines whether the loop should continue executing and increment modifies the control variable’s value, so that the loop-continuation condition eventually becomes false. • Typically, for statements are used for counter-controlled repetition and while statements are used for sentinel-controlled repetition. • The scope of a variable defines where it can be used in a program. For example, a local variable can be used only in the method that declares the variable and only from the point of declaration through the end of the method. • The initialization, loop-continuation condition and increment portions of a for statement can contain Stavros Dimitriou ©London South Bank University 1 Workshop: Lab 5 Engineering Software 1 arithmetic expressions. The increment of a for statement may also be negative, in which case it is really a decrement, and the loop counts downward. • If the loop-continuation condition in a for header is initially false, the program does not execute the for statement’s body. Instead, execution proceeds with the statement following the for. • The format specifier %20s outputs a String with a field width of 20 (i.e., at least 20 character positions). If the value to be output is less than 20 character positions wide, the value is right justified in the field by default. A value can be output left justified by simply preceding the field width with the minus sign (−) formatting flag. • Methods that perform common tasks and do not require objects are called static methods. • Java does not include an exponentiation operator. Instead, Math.pow(x, y) can be used to calculate the value of x raised to the yth power. The method receives two double arguments and returns a double value. • The comma (,) formatting flag in a format specifier (e.g., %,20.2f) indicates that a value should be output with a thousands separator. • The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. The format for the do…while statement is do { statement } while ( condition ); • The switch multiple-selection statement performs different actions based on the possible values of an integer variable or expression. Each action is associated with the value of a constant integral expression (i.e., a constant value of type byte, short, int or char, but not long) that the variable or expression on which the switch is based may assume. The switch statement consists of a block containing a sequence of case labels and an optional default case. • The expression in parentheses following keyword switch is called the controlling expression of the switch. A program compares the value of the controlling expression with each case label, and if a match occurs, the program executes the statements for that case. • The switch statement does not provide a mechanism for testing ranges of values, so every value that must be tested should be listed in a separate case label. • Listing cases consecutively with no statements between them enables those cases to perform the same set of statements. • Each case can have multiple statements. The switch statement differs from other control statements in that it does not require braces around multiple statements in each case. • Most switch statements use a break in each case to terminate the switch statement after processing the case. • The end-of-file indicator is a system-dependent keystroke combination which indicates that there is no more data to input. • Scanner method hasNext determines whether there is more data to input. This method returns the boolean value true if there is more data; otherwise, it returns false. • The break statement, when executed in one of the repetition statements, causes immediate exit from that statement. Execution continues with the first statement after the control statement. • The continue statement, when executed in a while, for or do…while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. • Logical operators enable programmers to form complex conditions by combining simple conditions. The logical operators are && (conditional AND), || (conditional OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (logical NOT). • The && (conditional AND) operator can be used to ensure that two conditions are both true before choosing a certain path of execution. • The || (conditional OR) operator can be used to ensure that either or both of two conditions are true before choosing a certain path of execution. • The parts of an expression containing && or || operators are evaluated only until it is known whether the condition is true or false. This feature of conditional AND and conditional OR expressions is called short- circuit evaluation. • The boolean logical AND (&) and boolean logical inclusive OR (|) operators work identically to the && Stavros Dimitriou ©London South Bank University 2 Workshop: Lab 5 Engineering Software 1 (conditional AND) and || (conditional OR) operators, with one exception: The boolean logical operators always evaluate both of their operands (i.e., they do not perform short-circuit evaluation). • A simple condition containing the boolean logical exclusive OR (^) operator is true if and only if one of its operands is true and the other is false. If both operands are true or both are false, the entire condition is false. • The ! (logical NOT, also called logical negation or logical complement) operator enables a programmer to “reverse” the meaning of a condition. The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical negation operator) is false. In most cases, the programmer can avoid using logical negation by expressing the condition differently with an appropriate relational or equality operator. • Unlike the logical operators &&, ||, &, | and ^, which are binary operators that combine two conditions, the logical negation operator is a unary operator that has only a single condition as an operand. • The %b format specifier causes the value of a boolean expression to be output as the word “true” or the word “false” based on the expression’s value. • Any form of control ever needed in a Java program can be expressed in terms of sequence, selection and repetition statements, and these can be combined in only two ways—stacking and nesting. Part A: Reinforce your understanding of key Java programming concepts Exercise 1: After reading the background above along with lecture notes, answer the given questions. The questions are intended to test and reinforce your understanding of key concepts. For each term in the left column, write the letter for the description from the right column that best matches the term. Stavros Dimitriou ©London South Bank University 3 Workshop: Lab 5 Engineering Software 1 Exercise 2: Answer the following questions in your logbook. Your answers should be as concise as possible; aim for two or three sentences. 1. What is required to perform counter-controlled repetition? 2. Explain why placing a semicolon after the header of a for statement is a logic error and not a compilation error. 3. Differentiate between the while and the do… while repetition statements. 4. Explain why an infinite loop can occur and how one can be prevented. Part B: Java programs Exercise 1: While and For repetition statement The following example uses the while repetition statement to formalize the elements required to perform counter-controlled repetition. 1. Analyze the structure of the following Java program. 2. Understand the program and predict the outcome in your logbook. __________________________________________________________ // WhileCounter.java // Counter-controlled repetition with the while repetition statement. public class WhileCounter { public static void main( String args[] ) { int counter = 1; // declare and initialize control variable while ( counter <= 10 ) // loop-continuation condition { System.out.printf( "%d ", counter ); ++counter; // increment control variable by 1 } // end while System.out.println(); // output a newline } // end main } // end class WhileCounter __________________________________________________________ 3. Create, Compile and Run the program. Stavros Dimitriou ©London South Bank University 4 Workshop: Lab 5 Engineering Software 1 The while statement can be used to implement any counter-controlled loop. Java also provides the for repetition statement, which specifies the counter-controlled-repetition details in a single line of code. 4. Analyze the structure of the following Java program. 5. Understand the program and predict the outcome in your logbook. __________________________________________________________ // ForCounter.java // Counter-controlled repetition with the for repetition statement. public class ForCounter { public static void main( String args[] ) { // for statement header includes initialization, // loop-continuation condition and increment for ( int counter = 1; counter <= 10; counter++ ) System.out.printf( "%d ", counter ); System.out.println(); // output a newline } // end main } // end class ForCounter __________________________________________________________ 6. Create, Compile and Run the program. Exercise 2: Summing the Even Integers from 2 to 20 In this example we consider two sample applications that demonstrate simple uses of for. The following program uses a for statement to sum the even integers from 2 to 20 and store the result in an int variable called total. 1. Analyze the structure of the following Java program. 2. Understand the program and predict the outcome in your logbook. __________________________________________________________ // Sum.java // Summing integers with the for statement. public class Sum { public static void main( String args[] ) { int total = 0; // initialize total // total even integers from 2 through 20 for ( int number = 2; number <= 20; number += 2 ) total += number; System.out.printf( "Sum is %d\n", total ); // display results } // end main } // end class Sum __________________________________________________________ 3. Create, Compile and Run the program. Stavros Dimitriou ©London South Bank University 5 Workshop: Lab 5 Engineering Software 1 Exercise 3: do… while Repetition Statement The do…while repetition statement is similar to the while statement. In the while, the program tests the loop-continuation condition at the beginning of the loop, before executing the loop’s body. If the condition is false, the body never executes. The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once. When a do…while statement terminates, execution continues with the next statement in sequence. 1. Analyze the structure of the following Java program. 2. Understand the program and predict the outcome in your logbook. __________________________________________________________ // DoWhileTest.java // do...while repetition statement. public class DoWhileTest { public static void main( String args[] ) { int counter = 1; // initialize counter do { System.out.printf( "%d ", counter ); ++counter; } while ( counter <= 10 ); // end do...while System.out.println(); // outputs a newline } // end main } // end class DoWhileTest __________________________________________________________ 3. Create, Compile and Run the program. Exercise 4: switch Multiple-Selection Statement We discussed the if single-selection statement and the if…else double-selection statement in previous Lab. Java provides the switch multiple-selection statement to perform different actions based on the possible values of an integer variable or expression. Each action. is associated with the value of a constant integral expression (i.e., a constant value of type byte, short, int or char, but not long) that the variable or expression on which the switch is based may assume. 1. Analyze the structure of the following Java application. 2. Understand the program and predict the outcome in your logbook. __________________________________________________________ // 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 Stavros Dimitriou ©London South Bank University 6 Workshop: Lab 5 Engineering Software 1 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 // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // 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() ); } // end method displayMessage // input arbitrary number of grades from user public void inputGrades() { Scanner input = new Scanner( System.in ); 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 typed then press Enter", "On Windows type z then press Enter" ); // loop until user enters the end-of-file indicator while ( input.hasNext() ) { grade = input.nextInt(); // read grade total += grade; // add grade to total ++gradeCounter; // increment number of grades // 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 grade ) { // determine which grade was entered switch ( grade / 10 ) { case 9: // grade was between 90 case 10: // and 100 ++aCount; // increment aCount Stavros Dimitriou ©London South Bank University 7 Workshop: Lab 5 Engineering Software 1 break; // necessary to exit switch case 8: // grade was between 80 and 89 ++bCount; // increment bCount break; // exit switch case 7: // grade was between 70 and 79 ++cCount; // increment cCount break; // exit switch case 6: // grade was between 60 and 69 ++dCount; // increment dCount break; // exit switch default: // grade was less than 60 ++fCount; // increment fCount break; // optional; will exit switch anyway } // end switch } // end method incrementLetterGradeCounter // display a report based on the grades entered by user public void displayGradeReport() { System.out.println( "\nGrade Report:" ); // if user entered at least one grade... if ( gradeCounter != 0 ) { // calculate average of all grades entered double average = (double) total / gradeCounter; // output summary of results System.out.printf( "Total of the %d grades entered is %d\n", gradeCounter, total ); System.out.printf( "Class average is %.2f\n", average ); System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", "Number of students who received each grade:", "A: ", aCount, // display number of A grades "B: ", bCount, // display number of B grades "C: ", cCount, // display number of C grades "D: ", dCount, // display number of D grades "F: ", fCount ); // display number of F grades } // end if else // no grades were entered, so output appropriate message System.out.println( "No grades were entered" ); } // end method displayGradeReport } // end class GradeBook __________________________________________________________ // GradeBookTest.java // Create GradeBook object, input grades and display grade report. public class GradeBookTest { public static void main( String args[] ) { // create GradeBook object myGradeBook and // pass course name to constructor GradeBook myGradeBook = new GradeBook( "CS101 Introduction to Java Programming" ); myGradeBook.displayMessage(); // display welcome message myGradeBook.inputGrades(); // read grades from user myGradeBook.displayGradeReport(); // display report based on grades } // end main } // end class GradeBookTest __________________________________________________________ Stavros Dimitriou ©London South Bank University 8 Workshop: Lab 5 Engineering Software 1 3. Create, Compile and Run the Java application. Exercise 5: break and continue Statements In addition to selection and repetition statements, Java provides statements break and continue to alter the flow of control. The preceding section showed how break can be used to terminate a switch statement’s execution. The break statement, when executed in a while, for, do…while or switch, causes immediate exit from that statement. Execution continues with the first statement after the control statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch. The continue statement, when executed in a while, for or do…while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. In while and do…while statements, the program evaluates the loop-continuation test immediately after the continue statement executes. In a for statement, the increment expression executes, then the program evaluates the loop-continuation test. 1. Analyze the structure of the following Java program. 2. Understand the program and predict the outcome in your logbook. __________________________________________________________ // BreakTest.java // break statement exiting a for statement. public class BreakTest { public static void main( String args[] ) { int count; // control variable also used after loop terminates for ( count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, break; // terminate loop System.out.printf( "%d ", count ); } // end for System.out.printf( "\nBroke out of loop at count = %d\n", count ); } // end main } // end class BreakTest __________________________________________________________ 3. Create, Compile and Run the program. 4. Analyze the structure of the following Java program. 5. Understand the program and predict the outcome in your logbook. __________________________________________________________ // ContinueTest.java // continue statement terminating an iteration of a for statement. public class ContinueTest { public static void main( String args[] ) { for ( int count = 1; count <= 10; count++ ) // loop 10 times { if ( count == 5 ) // if count is 5, continue; // skip remaining code in loop Stavros Dimitriou ©London South Bank University 9 Workshop: Lab 5 Engineering Software 1 System.out.printf( "%d ", count ); } // end for System.out.println( "\nUsed continue to skip printing 5" ); } // end main } // end class ContinueTest __________________________________________________________ 6. Create, Compile and Run the program. Exercise 6: Logical Operators Java provides logical operators to enable programmers to form more complex conditions by combining simple conditions. The logical operators are && (conditional AND), || (conditional OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (logical NOT). 1. Analyze the structure of the following Java program. 2. Understand the program and predict the outcome in your logbook. __________________________________________________________ // LogicalOperators.java // Logical operators. public class LogicalOperators { public static void main( String args[] ) { // create truth table for && (conditional AND) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional AND (&&)", "false && false", ( false && false ), "false && true", ( false && true ), "true && false", ( true && false ), "true && true", ( true && true ) ); // create truth table for || (conditional OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Conditional OR (||)", "false || false", ( false || false ), "false || true", ( false || true ), "true || false", ( true || false ), "true || true", ( true || true ) ); // create truth table for & (boolean logical AND) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical AND (&)", "false & false", ( false & false ), "false & true", ( false & true ), "true & false", ( true & false ), "true & true", ( true & true ) ); // create truth table for | (boolean logical inclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical inclusive OR (|)", "false | false", ( false | false ), "false | true", ( false | true ), "true | false", ( true | false ), "true | true", ( true | true ) ); // create truth table for ^ (boolean logical exclusive OR) operator System.out.printf( "%s\n%s: %b\n%s: %b\n%s: %b\n%s: %b\n\n", "Boolean logical exclusive OR (^)", "false ^ false", ( false ^ false ), "false ^ true", ( false ^ true ), "true ^ false", ( true ^ false ), Stavros Dimitriou ©London South Bank University 10 Workshop: Lab 5 Engineering Software 1 "true ^ true", ( true ^ true ) ); // create truth table for ! (logical negation) operator System.out.printf( "%s\n%s: %b\n%s: %b\n", "Logical NOT (!)", "!false", ( !false ), "!true", ( !true ) ); } // end main } // end class LogicalOperators __________________________________________________________ 3. Create, Compile and Run the program. Programming Assignment GUI and Graphics Case Study: Drawing Rectangles and Ovals This exercise introduces two other shapes you can draw using the graphics features in Java - rectangles and ovals. To draw rectangles and ovals, we call Graphics methods drawRect and drawOval, respectively, as demonstrated in the following java application. __________________________________________________________ // Shapes.java // Demonstrates drawing different shapes. import java.awt.Graphics; import javax.swing.JPanel; public class Shapes extends JPanel { private int choice; // user's choice of which shape to draw // constructor sets the user's choice public Shapes( int userChoice ) { choice = userChoice; } // end Shapes constructor // draws a cascade of shapes starting from the top left corner public void paintComponent( Graphics g ) { super.paintComponent( g ); for ( int i = 0; i < 10; i++ ) { // pick the shape based on the user's choice switch ( choice ) { case 1: // draw rectangles g.drawRect( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; case 2: // draw ovals g.drawOval( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; } // end switch } // end for } // end method paintComponent } // end class Shapes __________________________________________________________ Stavros Dimitriou ©London South Bank University 11 Workshop: Lab 5 Engineering Software 1 // ShapesTest.java // Test application that displays class Shapes. import javax.swing.JFrame; import javax.swing.JOptionPane; public class ShapesTest { public static void main( String args[] ) { // obtain user's choice String input = JOptionPane.showInputDialog( "Enter 1 to draw rectangles\n" + "Enter 2 to draw ovals" ); int choice = Integer.parseInt( input ); // convert input to int // create the panel with the user's input Shapes panel = new Shapes( choice ); JFrame application = new JFrame(); // creates a new JFrame application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.add( panel ); // add the panel to the frame application.setSize( 300, 300 ); // set the desired size application.setVisible( true ); // show the frame } // end main } // end class ShapesTest __________________________________________________________ 1. Analyze the structure of the Java application above. 2. Understand the program and predict the outcome in your logbook. 3. Create, Compile and Run the program. 4. Now, Draw 12 concentric circles in the center of a JPanel (see Fig. 1 below). The innermost circle should have a radius of 10 pixels, and each successive circle should have a radius 10 pixels larger than the previous one. Begin by finding the center of the JPanel. To get the upper-left corner of a circle, move up one radius and to the left one radius from the center. The width and height of the bounding rectangle is the diameter of the circle (twice the radius). Fig. 1: Drawing concentric circles. Stavros Dimitriou ©London South Bank University 12