Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.

Similar presentations


Presentation on theme: "Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition."— Presentation transcript:

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

2 4.4Control Structures Selection structures –Three types: if, if/else, and switch Repetition structures –Three types: while, do/while, and for

3 4.4Control Structures Complete list of Java keyword (not to be used as an identifier).

4 4.5The if Selection Structure Selection structure if ( studentGrade >= 60 ) System.out.println( "Passed" );

5 4.6The 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" );

6 4.6The if/else Selection Structure Flowchart of if/else structure truefalse print “Failed”print “Passed” grade >= 60

7 4.6The 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

8 4.6The 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" );

9 4.6The 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.

10 4.6The 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" );

11 4.6The 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." ); }

12 4.7The while Repetition Structure Example int product = 2; while ( product <= 1000 ) product = 2 * product; Flowchart product <= 1000 product = 2 * product true false

13 Grade averaging application 1// Fig. 4.7: Average1.java 2// Class average program with counter-controlled repetition 3import javax.swing.JOptionPane; 4 5public class Average1 { 6 public static void main( String args[] ) 7 { 8 int total, // sum of grades 9 gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 average; // average of all grades 12 String grade; // grade typed by user 13 14 // Initialization Phase 15 total = 0; // clear total 16 gradeCounter = 1; // prepare to loop 17 18 // Processing Phase 19 while ( gradeCounter <= 10 ) { // loop 10 times 20 21 // prompt for input and read grade from user 22 grade = JOptionPane.showInputDialog( 23 "Enter integer grade: " ); 24 25 // convert grade from a String to an integer 26 gradeValue = Integer.parseInt( grade ); 27 28 // add gradeValue to total 29 total = total + gradeValue; 30

14 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}

15 Program Output

16 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

17 Application using a sentinel controlled loop 1// Fig. 4.9: Average2.java 2// Class average program with sentinel-controlled repetition 3import javax.swing.JOptionPane; 4import java.text.DecimalFormat; 5 6public class Average2 { 7 public static void main( String args[] ) 8 { 9 int gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 total; // sum of grades 12 double average; // average of all grades 13 String input; // grade typed by user 14 15 // Initialization phase 16 total = 0; // clear total 17 gradeCounter = 0; // prepare to loop 18 19 // Processing phase 20 // prompt for input and read grade from user 21 input = JOptionPane.showInputDialog( 22 "Enter Integer Grade, -1 to Quit:" ); 23 24 // convert grade from a String to an integer 25 gradeValue = Integer.parseInt( input ); 26 27 while ( gradeValue != -1 ) { 28 // add gradeValue to total 29 total = total + gradeValue; 30

18 Application using a sentinel controlled loop 34 // prompt for input and read grade from user 35 input = JOptionPane.showInputDialog( 36 "Enter Integer Grade, -1 to Quit:" ); 37 38 // convert grade from a String to an integer 39 gradeValue = Integer.parseInt( input ); 40 } 41 42 // Termination phase 43 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 44 45 if ( gradeCounter != 0 ) { 46 average = (double) total / gradeCounter; 47 48 // display average of exam grades 49 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 else 55 JOptionPane.showMessageDialog( null, 56 "No grades were entered", "Class Average", 57 JOptionPane.INFORMATION_MESSAGE ); 58 59 System.exit( 0 ); // terminate the program 60 } 61}

19 Program Output

20 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 );

21 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" );

22 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;

23 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;

24 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 );

25 1. import 2. Class Average2 2.1 main 3. while loop 1// Fig. 4.9: Average2.java 2// Class average program with sentinel-controlled repetition 3import javax.swing.JOptionPane; 4import java.text.DecimalFormat; 5 6public class Average2 { 7 public static void main( String args[] ) 8 { 9 int gradeCounter, // number of grades entered 10 gradeValue, // grade value 11 total; // sum of grades 12 double average; // average of all grades 13 String input; // grade typed by user 14 15 // Initialization phase 16 total = 0; // clear total 17 gradeCounter = 0; // prepare to loop 18 19 // Processing phase 20 // prompt for input and read grade from user 21 input = JOptionPane.showInputDialog( 22 "Enter Integer Grade, -1 to Quit:" ); 23 24 // convert grade from a String to an integer 25 gradeValue = Integer.parseInt( input ); 26 27 27 while ( gradeValue != -1 ) { 28 // add gradeValue to total 29 total = total + gradeValue; 30 Test for sentinel value.

26 3. while loop 4. DecimalFormat 34 // prompt for input and read grade from user 35 input = JOptionPane.showInputDialog( 36 "Enter Integer Grade, -1 to Quit:" ); 37 38 // convert grade from a String to an integer 39 gradeValue = Integer.parseInt( input ); 40 } 41 42 // Termination phase 43 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 44 45 if ( gradeCounter != 0 ) { 46 46 average = (double) total / gradeCounter; 47 48 // display average of exam grades 49 JOptionPane.showMessageDialog( null, 50 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 else 55 JOptionPane.showMessageDialog( null, 56 "No grades were entered", "Class Average", 57 JOptionPane.INFORMATION_MESSAGE ); 58 59 System.exit( 0 ); // terminate the program 60 } 61} Cast total to a double. Output the formatted number.

27 Program Output

28 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".

29 1. import 2. Class Analysis 3. main 3.1 Initialize variables 4. while loop 5. Display results 1// Fig. 4.11: Analysis.java 2// Analysis of examination results. 3import javax.swing.JOptionPane; 4 5public class Analysis { 6 public static void main( String args[] ) 7 { 8 // initializing variables in declarations 9 int passes = 0, // number of passes 10 failures = 0, // number of failures 11 student = 1, // student counter 12 result; // one exam result 13 String input, // user-entered value 14 output; // output string 15 16 // process 10 students; counter-controlled loop 17 while ( student <= 10 ) { 18 input = JOptionPane.showInputDialog( 19 "Enter result (1=pass,2=fail)" ); 20 result = Integer.parseInt( input ); 21 22 22 if ( result == 1 ) 23 passes = passes + 1; 24 else 25 failures = failures + 1; 26 27 student = student + 1; 28 } 29 30 // termination phase 31 output = "Passed: " + passes + 32 "\nFailed: " + failures; Increment appropriate counter depending on input.

30 5. Display results Program Output 33 34 34 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

31 4.11Assignment Operators Assignment operators –Abbreviate assignment expressions c = c + 3; can be abbreviated as c += 3; –Uses addition assignment operator. Statements of the form variable = variable operator expression ; can be rewritten as variable operator = expression ; Other examples d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)

32 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

33 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

34 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 11 11 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 566556 566

35 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

36 4.13Primitive Data Types


Download ppt "Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition."

Similar presentations


Ads by Google