chapter 4 - control structures: part 1 outline 4.4control structures 4.5the if selection structure...

36
Chapter 4 - Control Structures: Part 1 Outline 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if/else Selection Structure 4.7 The while Repetition Structure 4.8 Counter-Controlled Repetition 4.9 Sentinel-Controlled Repetition 4.10 Nested Control Structures 4.11 Assignment Operators 4.12 Increment and Decrement Operators 4.13 Primitive Data Types ----- Some Class Exercises (9, 10, 19, 20….12)

Post on 20-Dec-2015

238 views

Category:

Documents


5 download

TRANSCRIPT

Chapter 4 - Control Structures: Part 1

Outline4.4 Control Structures4.5 The if Selection Structure4.6 The if/else Selection Structure4.7 The while Repetition Structure4.8 Counter-Controlled Repetition4.9 Sentinel-Controlled Repetition4.10 Nested Control Structures4.11 Assignment Operators4.12 Increment and Decrement Operators4.13 Primitive Data Types----- Some Class Exercises (9, 10, 19, 20….12)

4.4 Control Structures

• Selection structures– Three types: if, if/else, and switch

• Repetition structures

– Three types: while, do/while, and for

4.4 Control Structures

J ava Keywords

abstract boolean break byte case

catch char class continue default do double else extends false final finally float for if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try void volatile while

Keywords that are reserved but not used by Java const goto

• Complete list of Java keyword (not to be used as an identifier).

4.5 The if Selection Structure

• Selection structure

if ( studentGrade >= 60 ) System.out.println( "Passed" );

4.6 The if/else Selection Structure

• Selection structures– if

• Only performs an action if condition true– if/else

• Performs different action when condition true than when condition false

• Java code: if ( studentGrade >= 60 )

System.out.println( "Passed" );else

System.out.println( "Failed" );

4.6 The if/else Selection Structure

• Flowchart of if/else structure

truefalse

print “Failed” print “Passed”

grade >= 60

4.6 The if/else Selection Structure

• Nested if/else structures – Test for multiple cases

– Place if/else structures inside if/else structures

– If first condition met, other statements skipped

4.6 The if/else Selection Structure

if ( studentGrade >= 90 ) System.out.println( "A" );else if ( studentGrade >= 80 ) System.out.println( “C" ); else if ( studentGrade >= 70 ) System.out.println( “H" ); else if ( studentGrade >= 60 ) System.out.println( “G" ); else System.out.println( "F" );

4.6 The if/else Selection Structure

• Nested structures

if ( grade >= 90 ) System.out.println( "A" );else if ( grade >= 80 ) System.out.println( "B" );else if ( grade >= 70 ) System.out.println( "C" );else if ( grade >= 60 ) System.out.println( "D" );else System.out.println( "F" );

As before, else only executes when the if condition fails.

4.6 The if/else Selection Structure

• Important note– Java always associates else with previous if unless braces

({}) present• Dangling-else problem

if ( x > 5 ) if ( y > 5 ) System.out.println( "x and y are > 5" );else System.out.println( "x is <= 5" );

– Does not execute as it appears, executes as if ( x > 5 )

if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" );

4.6 The if/else Selection Structure

• Compound statements– Example:

if (grade >= 60) System.out.println( "Passed" );else { System.out.println( "Failed" ); System.out.println( "You must take this course again." );

}

4.7 The while Repetition Structure

• Exampleint product = 2;

while ( product <= 1000 ) product = 2 * product;

• Flowchart

product <= 1000 product = 2 * producttrue

false

Grade averaging application

1 // Fig. 4.7: Average1.java2 // Class average program with counter-controlled repetition3 import javax.swing.JOptionPane;45 public class Average1 {6 public static void main( String args[] ) 7 {8 int total, // sum of grades9 gradeCounter, // number of grades entered10 gradeValue, // grade value11 average; // average of all grades12 String grade; // grade typed by user13 14 // Initialization Phase15 total = 0; // clear total16 gradeCounter = 1; // prepare to loop17 18 // Processing Phase19 while ( gradeCounter <= 10 ) { // loop 10 times2021 // prompt for input and read grade from user22 grade = JOptionPane.showInputDialog(23 "Enter integer grade: " );2425 // convert grade from a String to an integer26 gradeValue = Integer.parseInt( grade );2728 // add gradeValue to total29 total = total + gradeValue; 30

Program Output

31 // add 1 to gradeCounter

32 gradeCounter = gradeCounter + 1;

33 }

34

35 // Termination Phase

36 average = total / 10; // perform integer division

37

38 // display average of exam grades

39 JOptionPane.showMessageDialog(

40 null, "Class average is " + average, "Class Average",

41 JOptionPane.INFORMATION_MESSAGE );

42

43 System.exit( 0 ); // terminate the program

44 }

45 }

Program Output

4.9 Sentinel-Controlled Repetition

• Many programs can be divided into three phases– Initialization

• Initializes the program variables

– Processing• Inputs data values and adjusts variables accordingly

– Calculation and Termination• Calculates and prints the final results

– Helps breakup of programs for top-down refinement

Application using a sentinel controlled loop

1 // Fig. 4.9: Average2.java2 // Class average program with sentinel-controlled repetition3 import javax.swing.JOptionPane;

4 import java.text.DecimalFormat;56 public class Average2 {7 public static void main( String args[] )8 {9 int gradeCounter, // number of grades entered10 gradeValue, // grade value11 total; // sum of grades12 double average; // average of all grades13 String input; // grade typed by user1415 // Initialization phase16 total = 0; // clear total17 gradeCounter = 0; // prepare to loop18 19 // Processing phase20 // prompt for input and read grade from user

21 input = JOptionPane.showInputDialog(22 "Enter Integer Grade, -1 to Quit:" );2324 // convert grade from a String to an integer25 gradeValue = Integer.parseInt( input );2627 while ( gradeValue != -1 ) {28 // add gradeValue to total29 total = total + gradeValue;30

Application using a sentinel controlled loop

34 // prompt for input and read grade from user35 input = JOptionPane.showInputDialog(36 "Enter Integer Grade, -1 to Quit:" );3738 // convert grade from a String to an integer39 gradeValue = Integer.parseInt( input );40 }4142 // Termination phase43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );4445 if ( gradeCounter != 0 ) {46 average = (double) total / gradeCounter; 4748 // display average of exam grades49 JOptionPane.showMessageDialog( null,50 "Class average is " + twoDigits.format( average ),51 "Class Average",52 JOptionPane.INFORMATION_MESSAGE );53 }

31 // add 1 to gradeCounter

32 gradeCounter = gradeCounter + 1;

33

54 else55 JOptionPane.showMessageDialog( null,56 "No grades were entered", "Class Average",57 JOptionPane.INFORMATION_MESSAGE );5859 System.exit( 0 ); // terminate the program60 }61 }

Program Output

4.9 Sentinel-Controlled Repetition

– Much of the code similar to previous example• Concentrate on differences

– Data type double• Can store floating-point (decimal) numbers

– Input first grade

12 double average; // average of all grades

21 input = JOptionPane.showInputDialog(22 "Enter Integer Grade, -1 to Quit:" );

25 gradeValue = Integer.parseInt( input );

4.9 Sentinel-Controlled Repetition

– Next value checked before total incremented

– DecimalFormat objects used to format numbers• 0 - format flag, specifies required digit position

• This format - at least one digit to left of decimal, exactly two to right of decimal

• 0's inserted if number does not meet requirements

27 while ( gradeValue != -1 ) {

29 total = total + gradeValue;

32 gradeCounter = gradeCounter + 1;

35 input = JOptionPane.showInputDialog(36 "Enter Integer Grade, -1 to Quit:" );

39 gradeValue = Integer.parseInt( input );

40 }

Comments removed

43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );

4.9 Sentinel-Controlled Repetition

– new - dynamic memory allocation operator• Creates an instance of an object

• Value in parenthesis after type initializes the object

– Cast operator (double)• Creates a floating-point copy of its operand (total)

– Explicit conversion

– Value in total still an integer

– Arithmetic• Can only be performed between variables of same type

• implicit conversion - promote a data type to another type

43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );

45 if ( gradeCounter != 0 ) {

46 average = (double) total / gradeCounter;

4.9 Sentinel-Controlled Repetition

– Copy of total is a double

– Cast operators• Parenthesis around type name: (type)

45 if ( gradeCounter != 0 ) {

46 average = (double) total / gradeCounter;

4.9 Sentinel-Controlled Repetition

– Use method format to output the formatted number• Using "0.00" format

49 JOptionPane.showMessageDialog( null,

50 "Class average is " + twoDigits.format( average ),

51 "Class Average",

52 JOptionPane.INFORMATION_MESSAGE );

1. import

2. Class Average2

2.1 main

3. while loop

1 // Fig. 4.9: Average2.java2 // Class average program with sentinel-controlled repetition3 import javax.swing.JOptionPane;

4 import java.text.DecimalFormat;56 public class Average2 {7 public static void main( String args[] )8 {9 int gradeCounter, // number of grades entered10 gradeValue, // grade value11 total; // sum of grades12 double average; // average of all grades13 String input; // grade typed by user1415 // Initialization phase16 total = 0; // clear total17 gradeCounter = 0; // prepare to loop18 19 // Processing phase20 // prompt for input and read grade from user

21 input = JOptionPane.showInputDialog(22 "Enter Integer Grade, -1 to Quit:" );2324 // convert grade from a String to an integer25 gradeValue = Integer.parseInt( input );26

2727 while ( gradeValue != -1 ) {28 // add gradeValue to total29 total = total + gradeValue;30

Test for sentinel value.

3. while loop

4. DecimalFormat

34 // prompt for input and read grade from user35 input = JOptionPane.showInputDialog(36 "Enter Integer Grade, -1 to Quit:" );3738 // convert grade from a String to an integer39 gradeValue = Integer.parseInt( input );40 }4142 // Termination phase43 DecimalFormat twoDigits = new DecimalFormat( "0.00" );4445 if ( gradeCounter != 0 ) {

4646 average = (double) total / gradeCounter; 4748 // display average of exam grades49 JOptionPane.showMessageDialog( null,

5050 "Class average is " + twoDigits.format( average ),51 "Class Average",52 JOptionPane.INFORMATION_MESSAGE );53 }

31 // add 1 to gradeCounter

32 gradeCounter = gradeCounter + 1;

33

54 else55 JOptionPane.showMessageDialog( null,56 "No grades were entered", "Class Average",57 JOptionPane.INFORMATION_MESSAGE );5859 System.exit( 0 ); // terminate the program60 }61 }

Cast total to a double.

Output the formatted number.

Program Output

4.10 Nested Control Structures

• Problem statement– A college has a list of test results (1 = pass, 2 = fail) for a

licensing exam for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition".

1. import

2. Class Analysis

3. main

3.1 Initialize variables

4. while loop

5. Display results

1 // Fig. 4.11: Analysis.java2 // Analysis of examination results.3 import javax.swing.JOptionPane;45 public class Analysis {6 public static void main( String args[] ) 7 {8 // initializing variables in declarations9 int passes = 0, // number of passes10 failures = 0, // number of failures11 student = 1, // student counter12 result; // one exam result13 String input, // user-entered value14 output; // output string1516 // process 10 students; counter-controlled loop17 while ( student <= 10 ) {18 input = JOptionPane.showInputDialog(19 "Enter result (1=pass,2=fail)" );20 result = Integer.parseInt( input );212222 if ( result == 1 )23 passes = passes + 1;24 else25 failures = failures + 1;2627 student = student + 1;28 }2930 // termination phase31 output = "Passed: " + passes +32 "\nFailed: " + failures;

Increment appropriate counter depending on input.

5. Display results

Program Output

33

3434 if( passes > 8 )

35 output = output + "\nRaise Tuition";

36

37 JOptionPane.showMessageDialog( null, output,

38 "Analysis of Examination Results",

39 JOptionPane.INFORMATION_MESSAGE );

40

41 System.exit( 0 );

42 }

43}

Check whether to raise tuition.

9 passes

1 fail

4.11Assignment Operators

• Assignment operators– Abbreviate assignment expressions

c = c + 3; can be abbreviated as c += 3; – Uses addition assignment operator.

• Statements of the formvariable = variable operator expression;

can be rewritten asvariable operator= expression;

• Other examples d -= 4 (d = d - 4)

e *= 5 (e = e * 5)f /= 3 (f = f / 3)g %= 9 (g = g % 9)

4.12Increment and Decrement Operators

• Other operators– Increment operator (++)

• Can be used instead of c += 1

– Decrement operator (--)• Can be used instead of c -= 1

• Pre/post– Preincrement/predecrement

• Operator before variable, i.e. ++c or --c• Change variable, then surrounding expression evaluated

– Postincrement/postdecrement• Operator after variable, i.e. c++ or c--• Variable changes, then surrounding expression evaluated

4.12Increment and Decrement Operators

• If variable not in an expression– Pre and post forms have the same effect

c++;

same as

++c;

• Upcoming program– Show differences between pre and post forms

1. Class Increment

2. main

3. Initialize variable

3.1 postincrement

3.2 preincrement

1// Fig. 4.14: Increment.java

2// Preincrementing and postincrementing

3

4public class Increment {

5 public static void main( String args[] )

6 {

7 int c;

8

9 c = 5;

10 System.out.println( c ); // print 5

1111 System.out.println( c++ ); // print 5 then postincrement

12 System.out.println( c ); // print 6

13

14 System.out.println(); // skip a line

15

16 c = 5;

17 System.out.println( c ); // print 5

18 System.out.println( ++c ); // preincrement then print 6

19 System.out.println( c ); // print 6

20 }

21}

556 566

4.13Primitive Data Types

• Primitive data types– char, byte, short, int, long, float, double, boolean

– Default values• boolean gets false, all other types are 0

4.13Primitive Data Types

Type Size in bits

Values Standard

boolean 8 true or false

char 16 ’\u0000’ to ’\uFFFF’ (ISO Unicode character set)

byte 8 –128 to +127

short 16 –32,768 to +32,767

int 32 –2,147,483,648 to +2,147,483,647

long 64 –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

float 32 –3.40292347E+38 to +3.40292347E+38

(IEEE 754 floating point)

double 64

–1.79769313486231570E+308 to +1.79769313486231570E+308

(IEEE 754 floating point)