2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while Repetition Statement 4.11 Compound Assignment Operators 4.12 Increment and Decrement Operators 4.13 Primitive Types Chapter 4 - Control Structures: Part 1
2003 Prentice Hall, Inc. All rights reserved Introduction We learn about Control Structures –Structured-programming principle –Control structures help build and manipulate objects (Chapter 8)
2003 Prentice Hall, Inc. All rights reserved Algorithms Algorithm –Series of actions in specific order The actions executed The order in which actions execute Program control –Specifying the order in which actions execute Control structures help specify this order
2003 Prentice Hall, Inc. All rights reserved Pseudocode Pseudocode –Informal language for developing algorithms –Not executed on computers –Helps developers “think out” algorithms
2003 Prentice Hall, Inc. All rights reserved Control Structures Sequential execution –Program statements execute one after the other Transfer of control –Three control structures can specify order of statements Sequence structure (default) Selection structure Repetition structure Activity diagram –Models the workflow (flowchart) Action-state symbols Transition arrows
2003 Prentice Hall, Inc. All rights reserved. 6 Fig 4.1 Sequence structure activity diagram. add grade to total add 1 to counter Corresponding Java statement: total = total + grade; Corresponding Java statement: counter = counter + 1;
2003 Prentice Hall, Inc. All rights reserved. 7
8 4.4 Control Structures Java has a sequence structure “built-in” Java provides three selection structures –if –if…else –switch Java provides three repetition structures –while –do…while –for Each of these words is a Java keyword
2003 Prentice Hall, Inc. All rights reserved if Single-Selection Statement Single-entry/single-exit control structure Perform action only when condition is true Action/decision programming model
2003 Prentice Hall, Inc. All rights reserved. 10 Fig 4.3 if single-selections statement activity diagram. [grade >= 60] [grade < 60] print “Passed” if (studentGrade >= 60) { System.out.println (“Passed”); }
2003 Prentice Hall, Inc. All rights reserved if…else Selection Statement Perform action only when condition is true Perform different specified action when condition is false Conditional operator ( ?: ) Nested if…else selection structures
2003 Prentice Hall, Inc. All rights reserved. 12 Fig 4.4 if…else double-selections statement activity diagram. [grade >= 60][grade < 60] print “Failed”print “Passed” if (studentGrade >= 60) { System.out.println (“Passed”); } else { System.out.println (“Failed”); }
2003 Prentice Hall, Inc. All rights reserved. 13 System.out.println (studentGrade >= 60 ? “Passed”: “Failed”); Conditional Operator (?:)
2003 Prentice Hall, Inc. All rights reserved. 14 Nested if…else selection structures if (studentGrade >= 90) System.out.println (“A”); else if (studentGrade >= 80) System.out.println (“B”); else if (studentGrade >= 70) System.out.println (“C”); else if (studentGrade >= 60) System.out.println (“D”); else System.out.println (“F”);
2003 Prentice Hall, Inc. All rights reserved while Repetition Statement Repeat action while condition remains true Condition should eventually become false (or never-ending loop)
2003 Prentice Hall, Inc. All rights reserved. 16 Fig 4.5 while repetition statement activity diagram. [product <= 1000] [product > 1000] double product value merge decision Corresponding Java statement: product = 2 * product; while (product <= 1000) { product = 2 * product; }
2003 Prentice Hall, Inc. All rights reserved Compound Assignment Operators Assignment Operators –Abbreviate assignment expressions –Any statement of form variable = variable operator expression ; –Can be written as variable operator = expression ; –e.g., addition assignment operator += c = c + 3 –can be written as c += 3
2003 Prentice Hall, Inc. All rights reserved. 18
2003 Prentice Hall, Inc. All rights reserved Increment and Decrement Operators Unary increment operator ( ++ ) –Increment variable’s value by 1 Unary decrement operator ( -- ) –Decrement variable’s value by 1 C++ is a language “one better than” C Preincrement / predecrement operator Postincrement / postdecrement operator
2003 Prentice Hall, Inc. All rights reserved. 20
2003 Prentice Hall, Inc. All rights reserved. Outline 21 Increment.java Line 13 postincrement Line 21 preincrement 1 // Fig. 4.14: Increment.java 2 // Preincrementing and postincrementing operators. 3 4 public class Increment { 5 6 public static void main( String args[] ) 7 { 8 int c; 9 10 // demonstrate postincrement 11 c = 5; // assign 5 to c 12 System.out.println( c ); // print 5 13 System.out.println( c++ ); // print 5 then postincrement 14 System.out.println( c ); // print System.out.println(); // skip a line // demonstrate preincrement 19 c = 5; // assign 5 to c 20 System.out.println( c ); // print 5 21 System.out.println( ++c ); // preincrement then print 6 22 System.out.println( c ); // print } // end main } // end class Increment Line 13 postincrements c Line 21 preincrements c
2003 Prentice Hall, Inc. All rights reserved Primitive Types Primitive types –“building blocks” for more complicated types Java is strongly typed –All variables in a Java program must have a type Java primitive types –portable across computer platforms that support Java
2003 Prentice Hall, Inc. All rights reserved. 23
2003 Prentice Hall, Inc. All rights reserved. 24 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition 5.3 for Repetition Statement 5.4 Examples Using the for Statement 5.5 do…while Repetition Statement 5.6 switch Multiple-Selection Statement 5.7 break and continue Statements 5.8 Labeled break and continue Statements 5.9 Logical Operators
2003 Prentice Hall, Inc. All rights reserved Essentials of Counter-Controlled Repetition Counter-controlled repetition requires: –Control variable (loop counter) –Initial value of the control variable –Increment/decrement of control variable through each loop –Condition that tests for the final value of the control variable
2003 Prentice Hall, Inc. All rights reserved. Outline 26 WhileCounter.ja va Line 14 Line 16 Line 18 1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class WhileCounter extends JApplet { 8 9 // draw lines on applet’s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 17 g.drawLine( 10, 10, 250, counter * 10 ); 18 ++counter; // increment } // end while } // end method paint } // end class WhileCounter Increment for counter Condition tests for counter ’s final value Control-variable name is counter Control-variable initial value is 1
2003 Prentice Hall, Inc. All rights reserved for Repetition Statement Handles counter-controlled-repetition details
2003 Prentice Hall, Inc. All rights reserved. Outline 28 ForCounter.java Line 16 int counter = 1; Line 16 counter <= 10; Line 16 counter++; 1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for statement. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class ForCounter extends JApplet { 8 9 // draw lines on applet’s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet // for statement header includes initialization, 15 // repetition condition and increment 16 for ( int counter = 1; counter <= 10; counter++ ) 17 g.drawLine( 10, 10, 250, counter * 10 ); } // end method paint } // end class ForCounter Condition tests for counter ’s final value Control-variable name is counter Control-variable initial value is 1 Increment for counter
2003 Prentice Hall, Inc. All rights reserved. 29 Fig. 5.3 for statement header components. for ( int counter = 1; counter <= 10; counter++ ) Increment of control variable Control variable Final value of control variable for which the condition is true for keyword Loop-continuation condition Initial value of control variable Required semicolon separator
2003 Prentice Hall, Inc. All rights reserved for Repetition Structure (cont.) for ( initialization ; loopContinuationCondition ; increment ) statement ; can usually be rewritten as: initialization ; while ( loopContinuationCondition ) { statement ; increment ; } init, condition, increment all optional Condition assumed to be true (unending loop) if omitted
2003 Prentice Hall, Inc. All rights reserved. 31 Fig. 5.4 for statement activity diagram. [ counter <= 10 ] [ counter > 10 ] int counter = 1 counter++ Determine whether the final value of control variable has been reached g.drawLine( 10, 10, 250, counter * 10 ); Establish initial value of control variable Draw a line on the applet Increment the control variable
2003 Prentice Hall, Inc. All rights reserved 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. Outline 33 Sum.java Line 12 1 // Fig. 5.5: Sum.java 2 // Summing integers with the for statement. 3 import javax.swing.JOptionPane; 4 5 public class Sum { 6 7 public static void main( String args[] ) 8 { 9 int total = 0; // initialize sum // total even integers from 2 through for ( int number = 2; number <= 100; number += 2 ) 13 total += number; // display results 16 JOptionPane.showMessageDialog( null, "The sum is " + total, 17 "Total Even Integers from 2 to 100", 18 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Sum increment number by 2 each iteration
2003 Prentice Hall, Inc. All rights reserved. Outline 34 Interest.java Lines Line 18 Line 19 1 // Fig. 5.6: Interest.java 2 // Calculating compound interest. 3 import java.text.NumberFormat; // class for numeric formatting 4 import java.util.Locale; // class for country-specific information 5 6 import javax.swing.JOptionPane; 7 import javax.swing.JTextArea; 8 9 public class Interest { public static void main( String args[] ) 12 { 13 double amount; // amount on deposit at end of each year 14 double principal = ; // initial amount before interest 15 double rate = 0.05; // interest rate // create NumberFormat for currency in US dollar format 18 NumberFormat moneyFormat = 19 NumberFormat.getCurrencyInstance( Locale.US ); // create JTextArea to display output 22 JTextArea outputTextArea = new JTextArea(); // set first line of text in outputTextArea 25 outputTextArea.setText( "Year\tAmount on deposit\n" ); 26 Java treats floating-points as type double NumberFormat can format numeric values as currency Display currency values with dollar sign ($)
2003 Prentice Hall, Inc. All rights reserved. Outline 35 Interest.java Lines // calculate amount on deposit for each of ten years 28 for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year 31 amount = principal * Math.pow( rate, year ); // append one line of text to outputTextArea 34 outputTextArea.append( year + "\t" + 35 moneyFormat.format( amount ) + "\n" ); } // end for // display results 40 JOptionPane.showMessageDialog( null, outputTextArea, 41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate the application } // end main } // end class Interest Calculate amount with for statement
2003 Prentice Hall, Inc. All rights reserved 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. Outline 37 DoWhileTest.jav a Lines // Fig. 5.7: DoWhileTest.java 2 // Using the do...while statement. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class DoWhileTest extends JApplet { 8 9 // draw lines on applet 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialize counter do { 17 g.drawOval( counter * 10, counter * 10, 18 counter * 20, counter * 20 ); 19 ++counter; 20 } while ( counter <= 10 ); // end do...while } // end method paint } // end class DoWhileTest Oval is drawn before testing counter ’s final value
2003 Prentice Hall, Inc. All rights reserved. 38 Fig. 5.8 do…while repetition statement activity diagram. action state [true] [false] condition
2003 Prentice Hall, Inc. All rights reserved switch Multiple-Selection Statement switch statement –Used for multiple selections –case followed by integer or character (case 10 or case ‘y’) –Multiple cases (without code) indicate the same thing done for each case case 3: case 5: case 7: x=y+z; break;
2003 Prentice Hall, Inc. All rights reserved. Outline 40 SwitchTest.java Lines 16-21: Getting user’s input 1 // Fig. 5.9: SwitchTest.java 2 // Drawing lines, rectangles or ovals based on user input. 3 import java.awt.Graphics; 4 5 import javax.swing.*; 6 7 public class SwitchTest extends JApplet { 8 int choice; // user's choice of which shape to draw 9 10 // initialize applet by obtaining user's choice 11 public void init() 12 { 13 String input; // user's input // obtain user's choice 16 input = JOptionPane.showInputDialog( 17 "Enter 1 to draw lines\n" + 18 "Enter 2 to draw rectangles\n" + 19 "Enter 3 to draw ovals\n" ); choice = Integer.parseInt( input ); // convert input to int } // end method init // draw shapes on applet's background 26 public void paint( Graphics g ) 27 { 28 super.paint( g ); // call paint method inherited from JApplet for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) 31 Get user’s input in JApplet
2003 Prentice Hall, Inc. All rights reserved. Outline 41 SwitchTest.java Line 32: controlling expression Line 32: switch statement Line switch ( choice ) { // determine shape to draw case 1: // draw a line 35 g.drawLine( 10, 10, 250, 10 + i * 10 ); 36 break; // done processing case case 2: // draw a rectangle 39 g.drawRect( 10 + i * 10, 10 + i * 10, i * 10, 50 + i * 10 ); 41 break; // done processing case case 3: // draw an oval 44 g.drawOval( 10 + i * 10, 10 + i * 10, i * 10, 50 + i * 10 ); 46 break; // done processing case default: // draw string indicating invalid value entered 49 g.drawString( "Invalid value entered", 50 10, 20 + i * 15 ); } // end switch } // end for } // end method paint } // end class SwitchTest default case for invalid entries switch statement determines which case label to execute, depending on controlling expression user input ( choice ) is controlling expression
2003 Prentice Hall, Inc. All rights reserved. Outline 42 SwitchTest.java
2003 Prentice Hall, Inc. All rights reserved. Outline 43 SwitchTest.java
2003 Prentice Hall, Inc. All rights reserved. 44 Fig switch multiple-selection statement activity diagram with break statements. case a action(s) break default action(s) [ true ] case b action(s) break case z action(s) break [ false ] case a [ true ] case b case z [ false ]
2003 Prentice Hall, Inc. All rights reserved 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 Escape early from loop or skip remainder of switch 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. Outline 46 BreakTest.java Line 12 Lines // Fig. 5.11: BreakTest.java 2 // Terminating a loop with break. 3 import javax.swing.JOptionPane; 4 5 public class BreakTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 int count; for ( count = 1; count <= 10; count++ ) { // loop 10 times if ( count == 5 ) // if count is 5, 15 break; // terminate loop output += count + " "; } // end for output += "\nBroke out of loop at count = " + count; 22 JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class BreakTest Loop 10 times exit for structure ( break ) when count equals 5
2003 Prentice Hall, Inc. All rights reserved. Outline 47 ContinueTest.ja va Line 11 Lines // Fig. 5.12: ContinueTest.java 2 // Continuing with the next iteration of a loop. 3 import javax.swing.JOptionPane; 4 5 public class ContinueTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; for ( int count = 1; count <= 10; count++ ) { // loop 10 times if ( count == 5 ) // if count is 5, 14 continue; // skip remaining code in loop output += count + " "; } // end for output += "\nUsed continue to skip printing 5"; 21 JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class ContinueTest Loop 10 timesSkip line 16 and proceed to line 11 when count equals 5
2003 Prentice Hall, Inc. All rights reserved 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 –Controversial – disguised “goto” statement! –Always a better way than labeled continue
2003 Prentice Hall, Inc. All rights reserved. Outline 49 BreakLabelTest. java Line 11 Line 14 Line 17 Lines // Fig. 5.13: BreakLabelTest.java 2 // Labeled break statement. 3 import javax.swing.JOptionPane; 4 5 public class BreakLabelTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; stop: { // labeled block // count 10 rows 14 for ( int row = 1; row <= 10; row++ ) { // count 5 columns 17 for ( int column = 1; column <= 5 ; column++ ) { if ( row == 5 ) // if row is 5, 20 break stop; // jump to end of stop block output += "* "; } // end inner for output += "\n"; } // end outer for 29 Loop 10 times stop is the labeled block Exit to line 35 (next slide) Nested loop 5 times
2003 Prentice Hall, Inc. All rights reserved. Outline 50 BreakLabelTest. java 30 // following line is skipped 31 output += "\nLoops terminated normally"; } // end labeled block JOptionPane.showMessageDialog( null, output, 36 "Testing break with a label", 37 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class BreakLabelTest
2003 Prentice Hall, Inc. All rights reserved. Outline 51 ContinueLabelTe st.java Line 11 Line 14 Line 17 Lines // Fig. 5.14: ContinueLabelTest.java 2 // Labeled continue statement. 3 import javax.swing.JOptionPane; 4 5 public class ContinueLabelTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; nextRow: // target label of continue statement // count 5 rows 14 for ( int row = 1; row <= 5; row++ ) { 15 output += "\n"; // count 10 columns per row 18 for ( int column = 1; column <= 10; column++ ) { // if column greater than row, start next row 21 if ( column > row ) 22 continue nextRow; // next iteration of labeled loop output += "* "; } // end inner for } // end outer for nextRow is the labeled blockLoop 5 timesNested loop 10 times continue to line 11 ( nextRow )
2003 Prentice Hall, Inc. All rights reserved. Outline 52 ContinueLabelTe st.java JOptionPane.showMessageDialog( null, output, 31 "Testing continue with a label", 32 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class ContinueLabelTest
2003 Prentice Hall, Inc. All rights reserved Logical Operators Logical operators –Allows for forming more complex conditions –Combines simple conditions Java logical operators –&& (conditional AND) (short circuit) –& (boolean logical AND) –|| (conditional OR) (short circuit) –| (boolean logical OR) –^ (boolean logical exclusive OR) –! (logical NOT) (project > 75 && exam>= 80)
2003 Prentice Hall, Inc. All rights reserved. 54
2003 Prentice Hall, Inc. All rights reserved. 55
2003 Prentice Hall, Inc. All rights reserved. Outline 56 LogicalOperator s.java Lines Lines // Fig. 5.19: LogicalOperators.java 2 // Logical operators. 3 import javax.swing.*; 4 5 public class LogicalOperators 6 7 public static void main( String args[] ) 8 { 9 // create JTextArea to display results 10 JTextArea outputArea = new JTextArea( 17, 20 ); // attach JTextArea to a JScrollPane so user can scroll results 13 JScrollPane scroller = new JScrollPane( outputArea ); // create truth table for && (conditional AND) operator 16 String output = "Logical AND (&&)" + 17 "\nfalse && false: " + ( false && false ) + 18 "\nfalse && true: " + ( false && true ) + 19 "\ntrue && false: " + ( true && false ) + 20 "\ntrue && true: " + ( true && true ); // create truth table for || (conditional OR) operator 23 output += "\n\nLogical OR (||)" + 24 "\nfalse || false: " + ( false || false ) + 25 "\nfalse || true: " + ( false || true ) + 26 "\ntrue || false: " + ( true || false ) + 27 "\ntrue || true: " + ( true || true ); 28 Conditional AND truth tableConditional OR truth table
2003 Prentice Hall, Inc. All rights reserved. Outline 57 LogicalOperator s.java Lines Lines Lines Lines // create truth table for & (boolean logical AND) operator 30 output += "\n\nBoolean logical AND (&)" + 31 "\nfalse & false: " + ( false & false ) + 32 "\nfalse & true: " + ( false & true ) + 33 "\ntrue & false: " + ( true & false ) + 34 "\ntrue & true: " + ( true & true ); // create truth table for | (boolean logical inclusive OR) operator 37 output += "\n\nBoolean logical inclusive OR (|)" + 38 "\nfalse | false: " + ( false | false ) + 39 "\nfalse | true: " + ( false | true ) + 40 "\ntrue | false: " + ( true | false ) + 41 "\ntrue | true: " + ( true | true ); // create truth table for ^ (boolean logical exclusive OR) operator 44 output += "\n\nBoolean logical exclusive OR (^)" + 45 "\nfalse ^ false: " + ( false ^ false ) + 46 "\nfalse ^ true: " + ( false ^ true ) + 47 "\ntrue ^ false: " + ( true ^ false ) + 48 "\ntrue ^ true: " + ( true ^ true ); // create truth table for ! (logical negation) operator 51 output += "\n\nLogical NOT (!)" + 52 "\n!false: " + ( !false ) + 53 "\n!true: " + ( !true ); outputArea.setText( output ); // place results in JTextArea 56 Logical NOT truth table Boolean logical exclusive OR truth table Boolean logical inclusive OR truth table Boolean logical AND truth table
2003 Prentice Hall, Inc. All rights reserved. Outline 58 LogicalOperator s.java 57 JOptionPane.showMessageDialog( null, scroller, 58 "Truth Tables", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class LogicalOperators