1 outline chapter 4 introduction control structures if single-selection statement if else selection...

35
1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators Increment and Decrement Operators Primitive Types Chapter 5 for Repetition Statement Examples Using the for Statement do…while Repetition Statement switch Multiple-Selection Statement break and continue Statements Logical Operators Chapter 4 and 5 - Control Structures

Post on 18-Dec-2015

225 views

Category:

Documents


1 download

TRANSCRIPT

1

OutlineChapter 4

Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators Increment and Decrement Operators Primitive Types

Chapter 5

for Repetition Statement Examples Using the for Statement do…while Repetition Statement switch Multiple-Selection Statement break and continue Statements Logical Operators

Chapter 4 and 5 - Control Structures

2

Introduction

• We learn about Control Structures– Control structures

3

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– do

• Each of these words is a Java keyword

Outline4

Average1.java gradeCounter

Line 21

1 // Fig. 4.7: Average1.java2 // Class-average program with counter-controlled repetition.3 import javax.swing.JOptionPane;4 5 public class Average1 {6 7 public static void main( String args[] ) 8 {9 int total; // sum of grades input by user10 int gradeCounter; // number of grade to be entered next11 int grade; // grade value12 int average; // average of grades13 14 String gradeString; // grade typed by user15 16 // initialization phase17 total = 0; // initialize total18 gradeCounter = 1; // initialize loop counter19 20 // processing phase21 while ( gradeCounter <= 10 ) { // loop 10 times22 23 // prompt for input and read grade from user24 gradeString = JOptionPane.showInputDialog(25 "Enter integer grade: " );26 27 // convert gradeString to int28 grade = Integer.parseInt( gradeString );29

Declare variables; gradeCounter is the counter

Continue looping as long as gradeCounter is less than or

equal to 10

Outline5

Average1.java

30 total = total + grade; // add grade to total31 gradeCounter = gradeCounter + 1; // increment counter32 33 } // end while34 35 // termination phase36 average = total / 10; // integer division37 38 // display average of exam grades39 JOptionPane.showMessageDialog( null, "Class average is " + average,40 "Class Average", JOptionPane.INFORMATION_MESSAGE );41 42 System.exit( 0 ); // terminate the program43 44 } // end main45 46 } // end class Average1

Outline6

Average1.java

Outline7

Average2.java

1 // Fig. 4.9: Average2.java2 // Class-average program with sentinel-controlled repetition.3 import java.text.DecimalFormat; // class to format numbers4 import javax.swing.JOptionPane;5 6 public class Average2 {7 8 public static void main( String args[] )9 {10 int total; // sum of grades11 int gradeCounter; // number of grades entered12 int grade; // grade value13 14 double average; // number with decimal point for average15 16 String gradeString; // grade typed by user17 18 // initialization phase19 total = 0; // initialize total20 gradeCounter = 0; // initialize loop counter21 22 // processing phase23 // get first grade from user 24 gradeString = JOptionPane.showInputDialog(25 "Enter Integer Grade or -1 to Quit:" );26 27 // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29

Outline8

Average2.java

Line 31

Line 45

30 // loop until sentinel value read from user31 while ( grade != -1 ) { 32 total = total + grade; // add grade to total33 gradeCounter = gradeCounter + 1; // increment counter34 35 // get next grade from user 36 gradeString = JOptionPane.showInputDialog(37 "Enter Integer Grade or -1 to Quit:" );38 39 // convert gradeString to int 40 grade = Integer.parseInt( gradeString ); 41 42 } // end while43 44 // termination phase45 DecimalFormat twoDigits = new DecimalFormat( "0.00" );46 47 // if user entered at least one grade...48 if ( gradeCounter != 0 ) {49 50 // calculate average of all grades entered51 average = (double) total / gradeCounter; 52 53 // display average with two digits of precision54 JOptionPane.showMessageDialog( null,55 "Class average is " + twoDigits.format( average ),56 "Class Average", JOptionPane.INFORMATION_MESSAGE );57 58 } // end if part of if...else59

loop until gradeCounter equals sentinel value (-1)

Format numbers to nearest hundredth

Outline9

Average2.java

60 else // if no grades entered, output appropriate message61 JOptionPane.showMessageDialog( null, "No grades were entered",62 "Class Average", JOptionPane.INFORMATION_MESSAGE );63 64 System.exit( 0 ); // terminate application65 66 } // end main67 68 } // end class Average2

Outline10

Analysis.java

Line 19

Line 29

1 // Fig. 4.11: Analysis.java2 // Analysis of examination results.3 import javax.swing.JOptionPane;4 5 public class Analysis {6 7 public static void main( String args[] ) 8 {9 // initializing variables in declarations10 int passes = 0; // number of passes 11 int failures = 0; // number of failures12 int studentCounter = 1; // student counter 13 int result; // one exam result14 15 String input; // user-entered value16 String output; // output string17 18 // process 10 students using counter-controlled loop19 while ( studentCounter <= 10 ) {20 21 // prompt user for input and obtain value from user22 input = JOptionPane.showInputDialog(23 "Enter result (1 = pass, 2 = fail)" );24 25 // convert result to int26 result = Integer.parseInt( input );27 28 // if result 1, increment passes; if...else nested in while29 if ( result == 1 ) 30 passes = passes + 1;

Loop until student counter is greater than 10

Nested control structure

Outline11

Analysis.java

31 32 else // if result not 1, increment failures 33 failures = failures + 1; 34 35 // increment studentCounter so loop eventually terminates36 studentCounter = studentCounter + 1; 37 38 } // end while39 40 // termination phase; prepare and display results41 output = "Passed: " + passes + "\nFailed: " + failures;42 43 // determine whether more than 8 students passed44 if ( passes > 8 )45 output = output + "\nRaise Tuition";46 47 JOptionPane.showMessageDialog( null, output,48 "Analysis of Examination Results",49 JOptionPane.INFORMATION_MESSAGE );50 51 System.exit( 0 ); // terminate application52 53 } // end main54 55 } // end class Analysis

12

Assignment Operators

• Assignment Operators• c = c + 3

– can be written as• c += 3

13

Assignment operator

Sample expression

Explanation Assigns

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;

+= c += 7 c = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g Fig. 4.12 Arithmetic assignment operators.

14

Increment and Decrement Operators

• Unary increment operator (++)– Increment variable’s value by 1

• Unary decrement operator (--)– Decrement variable’s value by 1

• Preincrement / predecrement operator• Post-increment / post-decrement operator

15

Operator Called Sample expression

Explanation

++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

Fig. 4.13 The increment and decrement operators.

Outline16

Increment.java

Line 13 postincrement

Line 21 preincrement

1 // Fig. 4.14: Increment.java2 // Preincrementing and postincrementing operators.3 4 public class Increment {5 6 public static void main( String args[] )7 {8 int c;9 10 // demonstrate postincrement11 c = 5; // assign 5 to c12 System.out.println( c ); // print 513 System.out.println( c++ ); // print 5 then postincrement14 System.out.println( c ); // print 6 15 16 System.out.println(); // skip a line17 18 // demonstrate preincrement19 c = 5; // assign 5 to c20 System.out.println( c ); // print 521 System.out.println( ++c ); // preincrement then print 622 System.out.println( c ); // print 6 23 24 } // end main25 26 } // end class Increment

556 

566

Line 13 postincrements c

Line 21 preincrements c

17

Primitive Types

• Primitive types– “building blocks” for more complicated types

• Java is strongly typed– All variables in a Java program must have a type

18

Type Size in bits Values Standard boolean true or false

[Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.]

char 16 '\u0000' to '\uFFFF' (0 to 65535)

(ISO Unicode character set)

byte 8 –128 to +127 (–27 to 27 – 1)

short 16 –32,768 to +32,767 (–215 to 215 – 1)

int 32 –2,147,483,648 to +2,147,483,647 (–231 to 231 – 1)

long 64 –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (–263 to 263 – 1)

float 32 Negative range: –3.4028234663852886E+38 to –1.40129846432481707e–45 Positive range: 1.40129846432481707e–45 to 3.4028234663852886E+38

(IEEE 754 floating point)

double 64 Negative range: –1.7976931348623157E+308 to –4.94065645841246544e–324 Positive range: 4.94065645841246544e–324 to 1.7976931348623157E+308

(IEEE 754 floating point)

Fig. 4.16 The J ava primitive types.

Outline19

WhileCounter.java

Line 14

Line 16

Line 18

1 // Fig. 5.1: WhileCounter.java2 // 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 background10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet13 14 int counter = 1; // initialization15 16 while ( counter <= 10 ) { // repetition condition17 g.drawLine( 10, 10, 250, counter * 10 );18 ++counter; // increment19 20 } // end while21 22 } // end method paint23 24 } // end class WhileCounter

Increment for counter

Condition tests for counter’s final value

Control-variable name is counter

Control-variable initial value is 1

Outline20

ForCounter.java

Line 16int counter = 1;

Line 16 counter <= 10;

Line 16 counter++;

1 // Fig. 5.2: ForCounter.java2 // 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 background10 public void paint( Graphics g )11 {12 super.paint( g ); // call paint method inherited from JApplet13 14 // for statement header includes initialization, 15 // repetition condition and increment16 for ( int counter = 1; counter <= 10; counter++ ) 17 g.drawLine( 10, 10, 250, counter * 10 );18 19 } // end method paint20 21 } // end class ForCounter

Condition tests for counter’s final value Control-variable name is counter

Control-variable initial value is 1Increment for counter

Outline21

Sum.java

Line 12

1 // Fig. 5.5: Sum.java2 // 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 sum10 11 // total even integers from 2 through 10012 for ( int number = 2; number <= 100; number += 2 )13 total += number; 14 15 // display results16 JOptionPane.showMessageDialog( null, "The sum is " + total,17 "Total Even Integers from 2 to 100",18 JOptionPane.INFORMATION_MESSAGE );19 20 System.exit( 0 ); // terminate application21 22 } // end main23 24 } // end class Sum

increment number by 2 each iteration

Outline22

Interest.java

Lines 13-15

Line 18

Line 19

1 // Fig. 5.6: Interest.java2 // Calculating compound interest.3 import java.text.NumberFormat; // class for numeric formatting 4 import java.util.Locale; // class for country-specific information5 6 import javax.swing.JOptionPane;7 import javax.swing.JTextArea;8 9 public class Interest {10 11 public static void main( String args[] )12 {13 double amount; // amount on deposit at end of each year14 double principal = 1000.0; // initial amount before interest15 double rate = 0.05; // interest rate 16 17 // create NumberFormat for currency in US dollar format18 NumberFormat moneyFormat = 19 NumberFormat.getCurrencyInstance( Locale.US ); 20 21 // create JTextArea to display output22 JTextArea outputTextArea = new JTextArea();23 24 // set first line of text in outputTextArea25 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 ($)

Outline23

Interest.java

Lines 28-31

27 // calculate amount on deposit for each of ten years 28 for ( int year = 1; year <= 10; year++ ) { 29 30 // calculate new amount for specified year 31 amount = principal * Math.pow( 1.0 + rate, year );32 33 // append one line of text to outputTextArea 34 outputTextArea.append( year + "\t" + 35 moneyFormat.format( amount ) + "\n" ); 36 37 } // end for 38 39 // display results40 JOptionPane.showMessageDialog( null, outputTextArea,41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE );42 43 System.exit( 0 ); // terminate the application44 45 } // end main46 47 } // end class Interest

Calculate amount with for statement

24

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

Outline25

DoWhileTest.java

Lines 16-20

1 // Fig. 5.7: DoWhileTest.java2 // 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 applet10 public void paint( Graphics g )11 {12 super.paint( g ); // call paint method inherited from JApplet13 14 int counter = 1; // initialize counter15 16 do { 17 g.drawOval( 110 - counter * 10, 110 - counter * 10,18 counter * 20, counter * 20 ); 19 ++counter; 20 } while ( counter <= 10 ); // end do...while 21 22 } // end method paint23 24 } // end class DoWhileTest

Oval is drawn before testing counter’s final value

26

switch Multiple-Selection Statement

• switch statement– Used for multiple selections

Outline27

SwitchTest.java

Lines 16-21:Getting user’s input

1 // Fig. 5.9: SwitchTest.java2 // 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 draw9 10 // initialize applet by obtaining user's choice11 public void init()12 {13 String input; // user's input14 15 // obtain user's choice16 input = JOptionPane.showInputDialog( 17 "Enter 1 to draw lines\n" +18 "Enter 2 to draw rectangles\n" +19 "Enter 3 to draw ovals\n" );20 21 choice = Integer.parseInt( input ); // convert input to int22 23 } // end method init24 25 // draw shapes on applet's background26 public void paint( Graphics g )27 {28 super.paint( g ); // call paint method inherited from JApplet29 30 for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9)31

Get user’s input in JApplet

Outline28

SwitchTest.java

Line 32:controlling expression

Line 32:switch statement

Line 48

32 switch ( choice ) { // determine shape to draw 33 34 case 1: // draw a line 35 g.drawLine( 10, 10, 250, 10 + i * 10 ); 36 break; // done processing case 37 38 case 2: // draw a rectangle 39 g.drawRect( 10 + i * 10, 10 + i * 10, 40 50 + i * 10, 50 + i * 10 ); 41 break; // done processing case 42 43 case 3: // draw an oval 44 g.drawOval( 10 + i * 10, 10 + i * 10, 45 50 + i * 10, 50 + i * 10 ); 46 break; // done processing case 47 48 default: // draw string indicating invalid value entered49 g.drawString( "Invalid value entered", 50 10, 20 + i * 15 ); 51 52 } // end switch 53 54 } // end for 55 56 } // end method paint57 58 } // 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

Outline29

SwitchTest.java

Outline30

SwitchTest.java

31

Fig. 5.10 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]

[true]

case b

case z

[false]

[false]

32

break and continue Statements

• 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

Outline33

BreakTest.java

Line 12

Lines 14-15

1 // Fig. 5.11: BreakTest.java2 // 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; 11 12 for ( count = 1; count <= 10; count++ ) { // loop 10 times13 14 if ( count == 5 ) // if count is 5, 15 break; // terminate loop16 17 output += count + " ";18 19 } // end for20 21 output += "\nBroke out of loop at count = " + count;22 JOptionPane.showMessageDialog( null, output );23 24 System.exit( 0 ); // terminate application25 26 } // end main27 28 } // end class BreakTest

Loop 10 times

exit for structure (break) when count equals 5

Outline34

ContinueTest.java

Line 11

Lines 13-14

1 // Fig. 5.12: ContinueTest.java2 // 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 = "";10 11 for ( int count = 1; count <= 10; count++ ) { // loop 10 times12 13 if ( count == 5 ) // if count is 5, 14 continue; // skip remaining code in loop15 16 output += count + " ";17 18 } // end for19 20 output += "\nUsed continue to skip printing 5";21 JOptionPane.showMessageDialog( null, output );22 23 System.exit( 0 ); // terminate application24 25 } // end main26 27 } // end class ContinueTest

Loop 10 times

Skip line 16 and proceed to line 11 when count equals 5

35

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)