2000 prentice hall, inc. all rights reserved. 1 chapter 5 - control structures - part 2 outline...

50
2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition 5.3 The for Repetition Structure 5.4 Examples Using the for Structure 5.5 The switch Multiple-Selection Structure 5.6 The do/while Repetition Structure 5.7 The break and continue Statements 5.8 The Labeled break and continue Statements 5.9 Logical Operators 5.10 Structured Programming Summary

Upload: ashley-mason

Post on 30-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

1

Chapter 5 - Control Structures - Part 2

Outline5.1 Introduction5.2 Essentials of Counter-Controlled Repetition5.3 The for Repetition Structure5.4 Examples Using the for Structure5.5 The switch Multiple-Selection Structure5.6 The do/while Repetition Structure5.7 The break and continue Statements5.8 The Labeled break and continue Statements5.9 Logical Operators5.10 Structured Programming Summary

Page 2: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

2

5.1 Introduction

• Before writing a program– Have a thorough understanding of problem

– Carefully planned approach for solving it

• While writing a program– Know what “building blocks” are available

– Use good programming principles

Page 3: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

3

5.2 Essentials of Counter-Controlled Repetition

• Counter-controlled repetition requires– Name of a control variable (loop counter)

– Initial value

– Condition that tests for the final value (i.e., whether looping should continue)

– Increment (or decrement)• Control variable modified each time through the loop

• Upcoming example– Counter-controlled repetition

– HTML file not shown

Page 4: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline4

1. import

2. Class WhileCounter

3. paint

3.1 Initialize counter

3.2 Loop

3.3 drawLine

3.4 Increment

Program Output

1// Fig. 5.1: WhileCounter.java

2// Counter-controlled repetition

3import java.awt.Graphics;

4import javax.swing.JApplet;

5

6public class WhileCounter extends JApplet {

7 public void paint( Graphics g )

8 {

9 int counter = 1; // initialization

10

11 while ( counter <= 10 ) { // repetition condition

12 g.drawLine( 10, 10, 250, counter * 10 );

13 ++counter; // increment

14 }

15 }

16}

Page 5: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

5

5.2 Essentials of Counter-Controlled Repetition

– Name and initialize the control variable• Declarations alone are not executable statements

• Assignment statements are executable statements

– Condition to test for final value (11)

– Method drawLine( x1, y1, x2, y2 )• Called using reference to Graphics object

• Draws line from (x1, y1) to (x2, y2)

– Increment

9 int counter = 1; // initialization

11 while ( counter <= 10 ) { // repetition condition

12 g.drawLine( 10, 10, 250, counter * 10 );

13 ++counter; // increment

Page 6: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

6

5.2 Essentials of Counter-Controlled Repetition

– Loop can be shortened• Initialize counter to zero

– Change loop to:

while ( ++counter <= 10 ) //repetition condition

g.drawLine( 10, 10, 250, counter *10 );

• Increment done inside while

Page 7: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

7

5.3 The for Repetition Structure

• Redo previous example– Use for structure

Page 8: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline8

Loop using for

Program Output

1// Fig. 5.2: ForCounter.java

2// Counter-controlled repetition with the for structure

3import java.awt.Graphics;

4import javax.swing.JApplet;

5

6public class ForCounter extends JApplet {

7 public void paint( Graphics g )

8 {

9 // Initialization, repetition condition and incrementing

10 // are all included in the for structure header.

11 for ( int counter = 1; counter <= 10; counter++ )

12 g.drawLine( 10, 10, 250, counter * 10 );

13 }

14}

Page 9: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

9

5.3 The for Repetition Structure

– Immediate observations• for "does it all" : initialization, condition, increment

– General format

for ( initialization; loopContinuationTest; increment )

statement

• If multiple statements needed, enclose in braces

• Control variable only exists in body of for structure

• If loopContinuationTest is initially false, body not executed

11 for ( int counter = 1; counter <= 10; counter++ )

12 g.drawLine( 10, 10, 250, counter * 10 );

Page 10: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

10

5.3 The for Repetition Structure

• May use arithmetic expressions in for loops– Let x =2, y=10

for ( int j = x; j <= 4 * x * y; j += y / x )

is equivalent tofor ( int j = 2; j <= 80; j += 5 )

• for can usually be written as a while loop:– Exception in section 5.7

initialization;while ( loopContinuationTest ) {

statement increment;

}

Page 11: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

11

5.3 The for Repetition Structure

11 for ( int counter = 1; counter <= 10; counter++ )

12 g.drawLine( 10, 10, 250, counter * 10 );

true

false

int counter = 1

counter <= 10 counter++

g.drawLine( 10, 10, 250, counter * 10 );

Establish initial value of control variable.

Determine if final value of control variable has been reached.

Body of loop (this may be many statements)

Increment the control variable.

Page 12: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

12

5.4 Examples Using the for Structure

• Problem– Calculate the value each year of a $1000 deposit, yielding

5% annually• Calculate the value for 10 years

– Use a = p (1 + r )• p - principal

• r - interest rate

• n - number of years

• a - amount on deposit after nth year

• Example program– Use a for loop to calculate interest

n

Page 13: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline13

Use for loop to calculate interest

1// Fig. 5.6: Interest.java

2// Calculating compound interest

3import java.text.DecimalFormat;

4import javax.swing.JOptionPane;

5import javax.swing.JTextArea;

6

7public class Interest {

8 public static void main( String args[] )

9 {

10 double amount, principal = 1000.0, rate = .05;

11

12 DecimalFormat precisionTwo = new DecimalFormat( "0.00" );

13 JTextArea outputTextArea = new JTextArea( 11, 20 );

14

15 outputTextArea.append( "Year\tAmount on deposit\n" );

16

17 for ( int year = 1; year <= 10; year++ ) {

18 amount = principal * Math.pow( 1.0 + rate, year );

19 outputTextArea.append( year + "\t" +

20 precisionTwo.format( amount ) + "\n" );

21 }

22

23 JOptionPane.showMessageDialog(

24 null, outputTextArea, "Compound Interest",

25 JOptionPane.INFORMATION_MESSAGE );

26

27 System.exit( 0 ); // terminate the application

28 }

29}

Page 14: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline14

Program Output

Page 15: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

15

5.4 Examples Using the for Structure

– Variables used

– Class DecimalFormat (package java.text)• Passed format control string "0.00"• Exactly two digits to right of decimal, at least one to left

• Method format returns formatted String

– Class JTextArea (package javax.swing)• GUI component, can display many lines of text

• Initialized to display 11 rows and 20 columns of text

• Allows us to scroll

10 double amount, principal = 1000.0, rate = .05;

12 DecimalFormat precisionTwo = new DecimalFormat( "0.00" );

13 JTextArea outputTextArea = new JTextArea( 11, 20 );

Page 16: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

16

5.4 Examples Using the for Structure

– Method append (of class JTextArea)• Add text to the String already in JTextArea object

• Initially contains empty string

– for loop executes 10 times– static method pow (class Math)

• Math.pow( x, y )• Raises x to the yth power

• Takes two doubles, returns a double

15 outputTextArea.append( "Year\tAmount on deposit\n" );

21 }

17 for ( int year = 1; year <= 10; year++ ) {18 amount = principal * Math.pow( 1.0 + rate, year );19 outputTextArea.append( year + "\t" +20 precisionTwo.format( amount ) + "\n" );

Page 17: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

17

5.4 Examples Using the for Structure

– static method showMessageDialog • Class JOptionPane• Up till now, displayed Strings• showMessageDialog can display a String or GUI

component, such as a JTextArea

– Beware rounding when performing monetary calculations• Do not use float or double for dollar amounts

• In exercises, explore use of integers

23 JOptionPane.showMessageDialog(

24 null, outputTextArea, "Compound Interest",

25 JOptionPane.INFORMATION_MESSAGE );

Page 18: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline18

1. import

2. Class Interest

2.1 Initialize variables

2.2 DecimalFormat

3. for loop

3.1 Math.pow

3.2 append

3.3 format

3.4 showMessageDialog

1// Fig. 5.6: Interest.java

2// Calculating compound interest

33import java.text.DecimalFormat;

4import javax.swing.JOptionPane;

5import javax.swing.JTextArea;

6

7public class Interest {

8 public static void main( String args[] )

9 {

10 double amount, principal = 1000.0, rate = .05;

11

12 DecimalFormat precisionTwo = new DecimalFormat( "0.00" );

1313 JTextArea outputTextArea = new JTextArea( 11, 20 );

14

15 outputTextArea.append( "Year\tAmount on deposit\n" );

16

17 for ( int year = 1; year <= 10; year++ ) {

1818 amount = principal * Math.pow( 1.0 + rate, year );

1919 outputTextArea.append( year + "\t" +

2020 precisionTwo.format( amount ) + "\n" );

21 }

22

2323 JOptionPane.showMessageDialog(

24 null, outputTextArea, "Compound Interest",

25 JOptionPane.INFORMATION_MESSAGE );

26

27 System.exit( 0 ); // terminate the application

28 }

29}

Notice the import statements required.

New JTextArea object initialized to hold 11 rows and 20 columns of text.

new operator used to create new objects.

Use method append to add to the String in the JTextArea object.

Notice the format of method Math.pow

Use method format to output the formatted number as a String.

Use the JTextArea reference as an argument to showMessageDialog

Page 19: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline19

Program Output

Page 20: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

20

5.5 The switch Multiple-Selection Structure

• switch statements– Useful to test a variable for different values

• Different action taken

• Format– Series of case labels and an optional default caseswitch ( value ){

case '1':actions

case '2':actions

default:actions

}– break; causes exit from structure

Page 21: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

21

5.5 The switch Multiple-Selection Structure

true

false

.

.

.

case a case a action(s) break

case b case b action(s) break

false

false

case z case z action(s) break

true

true

default action(s)

Page 22: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline22

Class SwitchTest

1// Fig. 5.7: SwitchTest.java2// Counting letter grades3import java.awt.Graphics;4import javax.swing.*;56public class SwitchTest extends JApplet {7 int choice; 89 public void init()10 {11 String input;1213 input = JOptionPane.showInputDialog( 14 "Enter 1 to draw lines\n" +15 "Enter 2 to draw rectangles\n" +16 "Enter 3 to draw ovals\n" );1718 choice = Integer.parseInt( input );19 }2021 public void paint( Graphics g )22 {23 for ( int i = 0; i < 10; i++ ) { 24 switch( choice ) {25 case 1:26 g.drawLine( 10, 10, 250, 10 + i * 10 );27 break;28 case 2:29 g.drawRect( 10 + i * 10, 10 + i * 10,30 50 + i * 10, 50 + i * 10 );31 break;

Page 23: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline23

Program Output

34 50 + i * 10, 50 + i * 10 );

35 break;

36 default:

37 JOptionPane.showMessageDialog(

38 null, "Invalid value entered" );

39 } // end switch

40 } // end for

41 } // end paint()

42} // end class SwitchTest

32 case 3:33 g.drawOval( 10 + i * 10, 10 + i * 10,

Page 24: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline24

Program Output

Page 25: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

25

5.5 The switch Multiple-Selection Structure

– Method init• Get input from user

9 public void init()

10 {11 String input;1213 input = JOptionPane.showInputDialog( 14 "Enter 1 to draw lines\n" +

15 "Enter 2 to draw rectangles\n" +16 "Enter 3 to draw ovals\n" );

1718 choice = Integer.parseInt( input );19 }

7 int choice;

Page 26: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

26

5.5 The switch Multiple-Selection Structure

– switch structure - compare choice to cases• case labels - can be constant integral values of type byte, short, int, long, and char

– Use single quotes to represent characters: 'A'– Can have multiple actions per case

• break - exits switch structure

• default label - optional, actions to take if no cases met

24 switch( choice ) {

25 case 1:

26 g.drawLine( 10, 10, 250, 10 + i * 10 );

27 break;

36 default:

37 JOptionPane.showMessageDialog(

38 null, "Invalid value entered" );

Page 27: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline27

1. Class SwitchTest

2. init

3. paint

3.1 for

3.2 switch

1// Fig. 5.7: SwitchTest.java2// Counting letter grades3import java.awt.Graphics;4import javax.swing.*;56public class SwitchTest extends JApplet {7 int choice; 89 public void init()10 {11 String input;1213 input = JOptionPane.showInputDialog( 14 "Enter 1 to draw lines\n" +15 "Enter 2 to draw rectangles\n" +16 "Enter 3 to draw ovals\n" );1718 choice = Integer.parseInt( input );19 }2021 public void paint( Graphics g )22 {23 for ( int i = 0; i < 10; i++ ) { 2424 switch( choice ) {2525 case 1:26 g.drawLine( 10, 10, 250, 10 + i * 10 );2727 break;28 case 2:29 g.drawRect( 10 + i * 10, 10 + i * 10,30 50 + i * 10, 50 + i * 10 );31 break;

Notice how case labels are used to test for the integer entered.

break exits the switch structure.

Place the value to compare inside the switch statement.

Page 28: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline28

Program Output

34 50 + i * 10, 50 + i * 10 );

35 break;

3636 default:

37 JOptionPane.showMessageDialog(

38 null, "Invalid value entered" );

39 } // end switch

40 } // end for

41 } // end paint()

42} // end class SwitchTest

32 case 3:33 g.drawOval( 10 + i * 10, 10 + i * 10,

default case

Page 29: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline29

Program Output

Page 30: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

30

5.6 The do/while Repetition Structure

• The do/while repetition structure – Similar to the while structure

– Condition for repetition tested after the body of the loop is performed

– Actions are performed at least once

• Format– do {

statement } while ( condition );

– Good practice to put brackets in, even if not required

Page 31: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

31

5.6 The do/while Repetition Structure

true

false

action(s)

condition

Page 32: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline32

1. Class DoWhileTest

2. paint

3. do/while loop

Program Output

1// Fig. 5.9: DoWhileTest.java

2// Using the do/while repetition structure

3import java.awt.Graphics;

4import javax.swing.JApplet;

5

6public class DoWhileTest extends JApplet {

7 public void paint( Graphics g )

8 {

9 int counter = 1;

10

11 do {

1212 g.drawOval( 110 - counter * 10, 110 - counter * 10,

13 counter * 20, counter * 20 );

14 ++counter;

15 } while ( counter <= 10 );

16 }

17}Method drawOval( x1, y1, width, height )

Same arguments as drawRect, but the rectangle defines the oval's bounding box.

Notice format of do/while loop.

Page 33: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

33

5.7 The break and continue Statements

• break– Immediate exit from while, for, do/while or switch– Program continues with the first statement after the structure

– Common uses of the break statement• Escape early from a loop

• Skip the remainder of a switch structure

Page 34: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

34

5.7 The break and continue Statements

• continue– Skips the remaining statements in body of while, for or do/while

• Proceeds with the next iteration of the loop

– while and do/while• Loop-continuation test is evaluated immediately after continue

– for structure• Increment expression is executed, then the loop-continuation

test is evaluated

Page 35: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline35

1. Class BreakTest

2. main

2.1 for loop

2.2 break

Program Output

1// Fig. 5.11: BreakTest.java2// Using the break statement in a for structure3import javax.swing.JOptionPane;45public class BreakTest {6 public static void main( String args[] )7 {8 String output = "";9 int count;1011 for ( count = 1; count <= 10; count++ ) {12 if ( count == 5 )

1313 break; // break loop only if count == 51415 output += count + " ";16 }1718 output += "\nBroke out of loop at count = " + count;19 JOptionPane.showMessageDialog( null, output );20 System.exit( 0 );21 }22}

break causes an immediate exit from the loop.

Page 36: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline36

1. Class ContinueTest

2. main

2.1 for loop

2.2 continue

Program Output

1// Fig. 5.12: ContinueTest.java2// Using the continue statement in a for structure3import javax.swing.JOptionPane;45public class ContinueTest {6 public static void main( String args[] )7 {8 String output = "";910 for ( int count = 1; count <= 10; count++ ) {11 if ( count == 5 )

1212 continue; // skip remaining code in loop13 // only if count == 51415 output += count + " ";16 }1718 output += "\nUsed continue to skip printing 5";19 JOptionPane.showMessageDialog( null, output );20 System.exit( 0 );21 }

continue skips the rest of the body and goes to the next iteration.

Page 37: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

37

5.8 The Labeled break and continue Statements

• Nested set of structures– break statement

• Can only break out of immediately enclosing structure

– Use labeled break statement• Label - identifier followed by colon, i.e. myLabel:• Breaks out of enclosing statement and any number of

repetition structures

• Program resumes after enclosing labeled compound statement

– Labeled continue statement• Skips statements in enclosing structure

• Continues with next iteration of enclosing labeled repetition structure

– Repetition structure preceded by a label

Page 38: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline38

1. Class BreakLabelTest

2. stop:

2.1 for loop

2.2 Nested for loop

2.3 break stop

1// Fig. 5.13: BreakLabelTest.java

2// Using the break statement with a label

3import javax.swing.JOptionPane;

4

5public class BreakLabelTest {

6 public static void main( String args[] )

7 {

8 String output = "";

9

1010 stop: { // labeled compound statement

11 for ( int row = 1; row <= 10; row++ ) {

12 for ( int column = 1; column <= 5 ; column++ ) {

13

14 if ( row == 5 )

1515 break stop; // jump to end of stop block

16

17 output += "* ";

18 }

19

20 output += "\n";

21 }

22

23 // the following line is skipped

24 output += "\nLoops terminated normally";

25 }

26

Begins labeled compound statement stop:

Labeled break statement to exit stop block.

Page 39: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline39

Program Output

27 JOptionPane.showMessageDialog(

28 null, output,"Testing break with a label",

29 JOptionPane.INFORMATION_MESSAGE );30 System.exit( 0 );

31 }

32}

Page 40: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline40

1. Class ContinueLabelTest

2. nextRow:

2.1 for loop

2.2 Nested for loop

2.3 continue nextRow

1// Fig. 5.14: ContinueLabelTest.java

2// Using the continue statement with a label3import javax.swing.JOptionPane;

4

5public class ContinueLabelTest {

6 public static void main( String args[] )7 {

8 String output = "";

9

1010 nextRow: // target label of continue statement

11 for ( int row = 1; row <= 5; row++ ) {

12 output += "\n";13

14 for ( int column = 1; column <= 10; column++ ) {

15

16 if ( column > row )17 continue nextRow; // next iteration of

18 // labeled loop

19 20 output += "* ";

21 }

22 }23

24 JOptionPane.showMessageDialog(

25 null, output,"Testing continue with a label",

26 JOptionPane.INFORMATION_MESSAGE );27 System.exit( 0 );

28 }

29}

This label applies to the following for loop (labeled repetition structure).

Labeled continue statement skips remaining statements, goes to next iteration of labeled repetition structure.

Page 41: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline41

Program Output

Page 42: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

42

5.9 Logical Operators

• Logical Operators– Till now, used <, >, ==, etc to test conditions

– Logical operators allow more complex conditions– && (logical AND)

• Returns true if both conditions are true

– || (logical OR) • Returns true if either of its conditions are true

– ! (logical NOT, logical negation)• Reverses the truth/falsity of its condition

• Unary operator, has one operand

– Short circuit evaluation• Evaluate left operand, decide whether to evaluate right

operand

• If left operand of && is false, will not evaluate right operand

Page 43: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

43

5.9 Logical Operators

• Logical Operators– ^ (Boolean logical exclusive OR)

• true if exactly one condition true

– Boolean logical AND (&) and boolean logical inclusive OR (|)

• Work identical to regular logical AND and logical OR

• Always evaluates both expressions (no short-circuit evaluation)

• Useful if right operand has a needed side effect

birthday == true | ++age >= 65

Page 44: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

44

5.9 Logical Operators

• Examples

Expression Result

true && false falsetrue || false true

!false truetrue ^ true false

– if ( ( gender == 1 ) && ( age >= 65 ) ) ++seniorFemales;

• seniorFemales updated if both conditions true

Page 45: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline45

1. Class LogicalOperators

1.1 JTextArea

1.2 JScrollPane

2. Logical operators

1// Fig. 5.19: LogicalOperators.java

2// Demonstrating the logical operators

3import javax.swing.*;

4

5public class LogicalOperators {

6 public static void main( String args[] )

7 {

88 JTextArea outputArea = new JTextArea( 17, 20 );

99 JScrollPane scroller = new JScrollPane( outputArea );

10 String output = "";

11

12 output += "Logical AND (&&)" +

1313 "\nfalse && false: " + ( false && false ) +

14 "\nfalse && true: " + ( false && true ) +

15 "\ntrue && false: " + ( true && false ) +

16 "\ntrue && true: " + ( true && true );

17

18 output += "\n\nLogical OR (||)" +

19 "\nfalse || false: " + ( false || false ) +

20 "\nfalse || true: " + ( false || true ) +

21 "\ntrue || false: " + ( true || false ) +

22 "\ntrue || true: " + ( true || true );

23

24 output += "\n\nBoolean logical AND (&)" +

25 "\nfalse & false: " + ( false & false ) +

26 "\nfalse & true: " + ( false & true ) +

27 "\ntrue & false: " + ( true & false ) +

28 "\ntrue & true: " + ( true & true );

29

JTextArea can display many lines of text. This one can display 17 rows and 20 columns.

This creates a JScrollPane object and initializes it with outputArea. This adds scrolling to outputArea.

Use the logical operators. Boolean values converted to Strings.

Page 46: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

Outline46

3. setText34 "\ntrue | true: " + ( true | true );

35

36 output += "\n\nBoolean logical exclusive OR (^)" +

37 "\nfalse ^ false: " + ( false ^ false ) +

38 "\nfalse ^ true: " + ( false ^ true ) +

39 "\ntrue ^ false: " + ( true ^ false ) +

40 "\ntrue ^ true: " + ( true ^ true );

41

42 output += "\n\nLogical NOT (!)" +

43 "\n!false: " + ( !false ) +

44 "\n!true: " + ( !true );

45

4646 outputArea.setText( output );

47 JOptionPane.showMessageDialog( null, scroller,

48 "Truth Tables", JOptionPane.INFORMATION_MESSAGE );

49 System.exit( 0 );

50 }

51 }

30 output += "\n\nBoolean logical inclusive OR (|)" +

31 "\nfalse | false: " + ( false | false ) +

32 "\nfalse | true: " + ( false | true ) +

33 "\ntrue | false: " + ( true | false ) +

Method setText replaces the String in the JTextArea.

Page 47: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

47

5.10Structured Programming Summary

• Structured programming– Easy to understand, test, debug and, modify programs

• Rules for structured programming– Rules developed by programming community

– Only single-entry/single-exit control structures are used

– Rules: 1) Begin with the “simplest flowchart”

2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence.

3) Any rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, while, do/while or for).

4) Rules 2 and 3 can be applied in any order and multiple times.

 

 

Page 48: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

485.10Structured Programming

Summary

.

.

.

Rule 2 Rule 2 Rule 2

Rule 1 - Begin with the simplest flowchart

Rule 2 - Any rectangle can be replaced by two rectangles in sequence

Page 49: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

495.10Structured Programming

Summary

Rule 3

Rule 3Rule 3

Rule 3 - Replace any rectangle with a control structure

Page 50: 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition

2000 Prentice Hall, Inc. All rights reserved.

505.10Structured Programming

Summary

• All programs can be broken down into 3 parts Sequence - trivial

Selection - if, if/else, or switch

Repetition - while, do/while, or for– Any selection can be rewritten as an if statement, and any

repetition can be rewritten as a while statement

• Programs can be reduced to– Sequence– if structure (selection)– while structure (repetition)

• The control structures can only be combined in two ways- nesting (rule 3) and stacking (rule 2)

– Promotes simplicity