Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Chapter 5 – Control Structures: Part 2 Outline 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 Introduction Essentials of Counter-Controlled Repetition for Repetition Statement Examples Using the for Statement do…while Repetition Statement switch Multiple-Selection Statement break and continue Statements Labeled break and continue Statements Logical Operators Structured Programming Summary (Optional Case Study) Thinking About Objects: Identifying Objects’ States and Activities 2003 Prentice Hall, Inc. All rights reserved. 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Outline // Fig. 5.1: WhileCounter.java // Counter-controlled repetition. import java.awt.Graphics; WhileCounter.ja va import javax.swing.JApplet; Control-variableCondition name is counter tests for counter’s final value Control-variable initial value is 1 public class WhileCounter extends JApplet { // draw lines on applet’s background public void paint( Graphics g ) { super.paint( g ); // call paint method inherited from JApplet int counter = 1; Line 14 Line 16 Increment Line for counter 18 // initialization while ( counter <= 10 ) { // repetition condition g.drawLine( 10, 10, 250, counter * 10 ); ++counter; // increment } // end while } // end method paint } // end class WhileCounter 2003 Prentice Hall, Inc. All rights reserved. 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 5.2: ForCounter.java // Counter-controlled repetition with the for statement. import java.awt.Graphics; import javax.swing.JApplet; Condition tests for Control-variable namecounter’s is counterfinal value public class ForCounter extends JApplet { Control-variable initial value is 1 applet’s background Increment for counter // draw lines on public void paint( Graphics g ) { super.paint( g ); // call paint method inherited from JApplet // for statement header includes initialization, // repetition condition and increment for ( int counter = 1; counter <= 10; counter++ ) g.drawLine( 10, 10, 250, counter * 10 ); Outline ForCounter.java Line 16 int counter = 1; Line 16 counter <= 10; Line 16 counter++; } // end method paint } // end class ForCounter 2003 Prentice Hall, Inc. All rights reserved. 4 for keyword Control variable Required semicolon separator Final value of control variable for which the condition is true Required semicolon separator for ( int counter = 1; counter <= 10; counter++ ) Initial value of control variable Fig. 5.3 Loop-continuation condition Increment of control variable for statement header components. 2003 Prentice Hall, Inc. All rights reserved. 5 5.3 for Repetition Structure (cont.) for ( initialization; loopContinuationCondition; increment ) statement; can usually be rewritten as: initialization; while ( loopContinuationCondition ) { statement; increment; } 2003 Prentice Hall, Inc. All rights reserved. 6 Establish initial value of control variable int counter = 1 [counter <= 10] Draw a line on the applet Increment the control variable [counter > 10] Determine whether the final value of control variable has been reached Fig. 5.4 g.drawLine( 10, 10, 250, counter * 10 ); for statement activity diagram. 2003 Prentice Hall, Inc. All rights reserved. counter++ 7 5.4 Examples Using the for Statement • Varying control variable in for statement – Vary control variable from 1 to 100 in increments of 1 • for ( int i = 1; i <= 100; i++ ) – Vary control variable from 100 to 1 in increments of –1 • for ( int i = 100; i >= 1; i-- ) – Vary control variable from 7 to 77 in increments of 7 • for ( int i = 7; i <= 77; i += 7 ) 2003 Prentice Hall, Inc. All rights reserved. 8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 5.5: Sum.java // Summing integers with the for statement. import javax.swing.JOptionPane; increment number by 2 each iteration public class Sum { public static void main( String args[] ) { int total = 0; // initialize sum Outline Sum.java Line 12 // total even integers from 2 through 100 for ( int number = 2; number <= 100; number += 2 ) total += number; // display results JOptionPane.showMessageDialog( null, "The sum is " + total, "Total Even Integers from 2 to 100", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Sum 2003 Prentice Hall, Inc. All rights reserved. 9 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 // Fig. 5.6: Interest.java Outline // Calculating compound interest. import java.text.NumberFormat; // class for numeric formatting Interest.java import java.util.Locale; // class for country-specific information import javax.swing.JOptionPane; import javax.swing.JTextArea; public class Interest { NumberFormat can format numeric values as currency Lines 13-15 Line 18 Line 19 public static void main( String args[] ) Display currency values with { sign ($) year double amount; // amount on deposit at dollar end of each double principal = 1000.0; // initial amount before interest double rate = 0.05; // interest rate // create NumberFormat for currency in US dollar format NumberFormat moneyFormat = NumberFormat.getCurrencyInstance( Locale.US ); // create JTextArea to display output JTextArea outputTextArea = new JTextArea(); // set first line of text in outputTextArea outputTextArea.setText( "Year\tAmount on deposit\n" ); 2003 Prentice Hall, Inc. All rights reserved. 10 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year amount = principal * Math.pow( 1.0 + rate, year ); Outline Interest.java Lines 28-31 // append one line of text to outputTextArea outputTextArea.append( year + "\t" + moneyFormat.format( amount ) + "\n" ); } // end for // display results JOptionPane.showMessageDialog( null, outputTextArea, "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate the application } // end main } // end class Interest 2003 Prentice Hall, Inc. All rights reserved. 11 5.5 do…while Repetition Statement • do…while structure – Similar to while structure – Tests loop-continuation after performing body of loop • i.e., loop body always executes at least once 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 12 Outline // Fig. 5.7: DoWhileTest.java // Using the do...while statement. import java.awt.Graphics; DoWhileTest.jav a import javax.swing.JApplet; Oval is drawn before testing counter’s final value public class DoWhileTest extends JApplet { Lines 16-20 // draw lines on applet public void paint( Graphics g ) { super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialize counter do { g.drawOval( 110 - counter * 10, 110 - counter * 10, counter * 20, counter * 20 ); ++counter; } while ( counter <= 10 ); // end do...while } // end method paint } // end class DoWhileTest 2003 Prentice Hall, Inc. All rights reserved. 13 action state [true] condition [false] Fig. 5.8 do…while repetition statement activity diagram. 2003 Prentice Hall, Inc. All rights reserved. 14 5.6 switch Multiple-Selection Statement • switch statement – Used for multiple selections 2003 Prentice Hall, Inc. All rights reserved. 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 29 30 31 // Fig. 5.9: SwitchTest.java // Drawing lines, rectangles or ovals based on user input. import java.awt.Graphics; import javax.swing.*; 15 Outline SwitchTest.java public class SwitchTest extends JApplet { int choice; // user's choice of which shape to draw Lines 16-21: Getting user’s input // initialize applet by obtaining user's choice public void init() { String input; // user's input Get user’s input in JApplet // obtain user's choice input = JOptionPane.showInputDialog( "Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" + "Enter 3 to draw ovals\n" ); choice = Integer.parseInt( input ); // convert input to int } // end method init // draw shapes on applet's background public void paint( Graphics g ) { super.paint( g ); // call paint method inherited from JApplet for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) 2003 Prentice Hall, Inc. All rights reserved. 16 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 switch ( choice ) { Outline // determine shape to draw case 1: // draw a line g.drawLine( 10, 10, 250, 10 + i * 10 ); break; // done processing case case 2: // draw a rectangle g.drawRect( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; // done processing case case 3: // draw an oval g.drawOval( 10 + i * 10, 10 + i * 10, 50 + i * 10, 50 + i * 10 ); break; // done processing case SwitchTest.java Line 32: controlling expression Line 32: switch statement Line 48 default: // draw string indicating invalid value entered g.drawString( "Invalid value entered", 10, 20 + i * 15 ); } // end switch } // end for } // end method paint } // end class SwitchTest 2003 Prentice Hall, Inc. All rights reserved. 17 Outline SwitchTest.java 2003 Prentice Hall, Inc. All rights reserved. 18 Outline SwitchTest.java 2003 Prentice Hall, Inc. All rights reserved. 19 [true] case a case a action(s) break case b action(s) break case z action(s) break [false] [true] case b [false] . . . [true] case z [false] default action(s) Fig. 5.10 switch multiple-selection statement activity diagram with break statements. 2003 Prentice Hall, Inc. All rights reserved. 20 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 2003 Prentice Hall, Inc. All rights reserved. 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.11: BreakTest.java // Terminating a loop with break. import javax.swing.JOptionPane; 21 Outline BreakTest.java public class BreakTest { Line 12 public static void main( String args[] ) { String output = ""; int count; for ( count = 1; count <= 10; count++ ) { if ( count == 5 ) break; Lines 14-15 // loop 10 times // if count is 5, // terminate loop output += count + " "; } // end for output += "\nBroke out of loop at count = " + count; JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class BreakTest 2003 Prentice Hall, Inc. All rights reserved. 22 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 Outline // Fig. 5.12: ContinueTest.java // Continuing with the next iteration of a loop. import javax.swing.JOptionPane; ContinueTest.ja va public class ContinueTest { Line 11 public static void main( String args[] ) { String output = ""; for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) continue; Lines 13-14 // loop 10 times // if count is 5, // skip remaining code in loop output += count + " "; } // end for output += "\nUsed continue to skip printing 5"; JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class ContinueTest 2003 Prentice Hall, Inc. All rights reserved. 5.8 Labeled break and continue Statements • Labeled block – Set of statements enclosed by {} – Preceded by a label • Labeled break statement – Exit from nested control structures – Proceeds to end of specified labeled block • Labeled continue statement – Skips remaining statements in nested-loop body – Proceeds to beginning of specified labeled block 2003 Prentice Hall, Inc. All rights reserved. 23 24 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 29 // Fig. 5.13: BreakLabelTest.java // Labeled break statement. import javax.swing.JOptionPane; BreakLabelTest. java public class BreakLabelTest { public static void main( String args[] ) { String output = ""; stop: { Outline Line 11 Line 14 // labeled block Line 17 // count 10 rows for ( int row = 1; row <= 10; row++ ) { Lines 19-20 // count 5 columns for ( int column = 1; column <= 5 ; column++ ) { if ( row == 5 ) break stop; output += "* // if row is 5, // jump to end of stop block "; } // end inner for output += "\n"; } // end outer for 2003 Prentice Hall, Inc. All rights reserved. 25 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // following line is skipped output += "\nLoops terminated normally"; } // end labeled block Outline BreakLabelTest. java JOptionPane.showMessageDialog( null, output, "Testing break with a label", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class BreakLabelTest 2003 Prentice Hall, Inc. All rights reserved. 26 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 Outline // Fig. 5.14: ContinueLabelTest.java // Labeled continue statement. import javax.swing.JOptionPane; public class ContinueLabelTest { public static void main( String args[] ) { String output = ""; nextRow: ContinueLabelTe st.java Line 11 Line 14 // target label of continue statement Line 17 // count 5 rows for ( int row = 1; row <= 5; row++ ) { output += "\n"; Lines 21-22 // count 10 columns per row for ( int column = 1; column <= 10; column++ ) { // if column greater than row, start next row if ( column > row ) continue nextRow; // next iteration of labeled loop output += "* "; } // end inner for } // end outer for 2003 Prentice Hall, Inc. All rights reserved. 27 29 30 31 32 33 34 35 36 37 38 Outline JOptionPane.showMessageDialog( null, output, "Testing continue with a label", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); ContinueLabelTe st.java // terminate application } // end main } // end class ContinueLabelTest 2003 Prentice Hall, Inc. All rights reserved. 28 5.9 Logical Operators • Logical operators – Allows for forming more complex conditions – Combines simple conditions • Java logical operators – – – – – – && & || | ^ ! (conditional AND) (boolean logical AND) (conditional OR) (boolean logical inclusive OR) (boolean logical exclusive OR) (logical NOT) 2003 Prentice Hall, Inc. All rights reserved. 29 expression1 && expression2 false false false false true false true false false true true true Fig. 5.15 && (conditional AND) operator truth table. expression1 expression2 expression1 expression2 expression1 || expression2 false false false false true true true false true true true true Fig. 5.16 || (conditional OR) operator truth table. 2003 Prentice Hall, Inc. All rights reserved. 30 expression1 ^ expression2 false false false false true true true false true true true false Fig. 5.17 ^ (boolean logical exclusive OR) operator truth table. expression1 expression2 expression !expression false true true false Fig. 5.18 ! (logical negation, or logical NOT) operator truth table. 2003 Prentice Hall, Inc. All rights reserved. 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.19: LogicalOperators.java // Logical operators. import javax.swing.*; public class LogicalOperators public static void main( String args[] ) { // create JTextArea to display results JTextArea outputArea = new JTextArea( 17, 20 ); 31 Outline LogicalOperator s.java Lines 16-20 Lines 23-27 // attach JTextArea to a JScrollPane so user can scroll results JScrollPane scroller = new JScrollPane( outputArea ); // create truth table for && (conditional AND) operator String output = "Logical AND (&&)" + "\nfalse && false: " + ( false && false ) + "\nfalse && true: " + ( false && true ) + "\ntrue && false: " + ( true && false ) + "\ntrue && true: " + ( true && true ); // create truth table for || (conditional OR) operator output += "\n\nLogical OR (||)" + "\nfalse || false: " + ( false || false ) + "\nfalse || true: " + ( false || true ) + "\ntrue || false: " + ( true || false ) + "\ntrue || true: " + ( true || true ); 2003 Prentice Hall, Inc. All rights reserved. 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // create truth table for & (boolean logical AND) operator output += "\n\nBoolean logical AND (&)" + "\nfalse & false: " + ( false & false ) + "\nfalse & true: " + ( false & true ) + "\ntrue & false: " + ( true & false ) + "\ntrue & true: " + ( true & true ); 32 Outline LogicalOperator s.java // create truth table for | (boolean logical inclusive OR) operator Lines output += "\n\nBoolean logical inclusive OR (|)" + "\nfalse | false: " + ( false | false ) + Lines "\nfalse | true: " + ( false | true ) + "\ntrue | false: " + ( true | false ) + Lines "\ntrue | true: " + ( true | true ); 30-34 // create truth table for ^ (boolean logical exclusive OR) operator Lines output += "\n\nBoolean logical exclusive OR (^)" + "\nfalse ^ false: " + ( false ^ false ) + "\nfalse ^ true: " + ( false ^ true ) + "\ntrue ^ false: " + ( true ^ false ) + "\ntrue ^ true: " + ( true ^ true ); 51-53 37-41 44-48 // create truth table for ! (logical negation) operator output += "\n\nLogical NOT (!)" + "\n!false: " + ( !false ) + "\n!true: " + ( !true ); outputArea.setText( output ); // place results in JTextArea 2003 Prentice Hall, Inc. All rights reserved. 57 58 59 60 61 62 63 64 JOptionPane.showMessageDialog( null, scroller, "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main 33 Outline LogicalOperator s.java } // end class LogicalOperators 2003 Prentice Hall, Inc. All rights reserved. 34 Operators Associativity Type ++ -right to left unary postfix ++ -- + ! right to left unary (type) * / % left to right multiplicative + left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right conditional AND || left to right conditional OR ?: right to left conditional = += - = *= /= %= right t o left assignment Fig. 5.20 Precedence/associativity of the operators discussed so far. 2003 Prentice Hall, Inc. All rights reserved. 35 5.10 Structured Programming Summary • Sequence structure – “built-in” to Java • Selection structure – if, if…else and switch • Repetition structure – while, do…while and for 2003 Prentice Hall, Inc. All rights reserved.