Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators.

Similar presentations


Presentation on theme: "1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators."— Presentation transcript:

1 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

2 2 Introduction We learn about Control Structures –Control structures

3 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

4 Outline 4 Average1.java gradeCounter Line 21 1 // Fig. 4.7: Average1.java 2 // 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 user 10 int gradeCounter; // number of grade to be entered next 11 int grade; // grade value 12 int average; // average of grades 13 14 String gradeString; // grade typed by user 15 16 // initialization phase 17 total = 0; // initialize total 18 gradeCounter = 1; // initialize loop counter 19 20 // processing phase 21 while ( gradeCounter <= 10 ) { // loop 10 times 22 23 // prompt for input and read grade from user 24 gradeString = JOptionPane.showInputDialog( 25 "Enter integer grade: " ); 26 27 // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29 Declare variables; gradeCounter is the counter Continue looping as long as gradeCounter is less than or equal to 10

5 Outline 5 Average1.java 30 total = total + grade; // add grade to total 31 gradeCounter = gradeCounter + 1; // increment counter 32 33 } // end while 34 35 // termination phase 36 average = total / 10; // integer division 37 38 // display average of exam grades 39 JOptionPane.showMessageDialog( null, "Class average is " + average, 40 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 41 42 System.exit( 0 ); // terminate the program 43 44 } // end main 45 46 } // end class Average1

6 Outline 6 Average1.java

7 Outline 7 Average2.java 1 // Fig. 4.9: Average2.java 2 // Class-average program with sentinel-controlled repetition. 3 import java.text.DecimalFormat; // class to format numbers 4 import javax.swing.JOptionPane; 5 6 public class Average2 { 7 8 public static void main( String args[] ) 9 { 10 int total; // sum of grades 11 int gradeCounter; // number of grades entered 12 int grade; // grade value 13 14 double average; // number with decimal point for average 15 16 String gradeString; // grade typed by user 17 18 // initialization phase 19 total = 0; // initialize total 20 gradeCounter = 0; // initialize loop counter 21 22 // processing phase 23 // 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

8 Outline 8 Average2.java Line 31 Line 45 30 // loop until sentinel value read from user 31 while ( grade != -1 ) { 32 total = total + grade; // add grade to total 33 gradeCounter = gradeCounter + 1; // increment counter 34 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 while 43 44 // termination phase 45 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 entered 51 average = (double) total / gradeCounter; 52 53 // display average with two digits of precision 54 JOptionPane.showMessageDialog( null, 55 "Class average is " + twoDigits.format( average ), 56 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 57 58 } // end if part of if...else 59 loop until gradeCounter equals sentinel value ( -1 ) Format numbers to nearest hundredth

9 Outline 9 Average2.java 60 else // if no grades entered, output appropriate message 61 JOptionPane.showMessageDialog( null, "No grades were entered", 62 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 63 64 System.exit( 0 ); // terminate application 65 66 } // end main 67 68 } // end class Average2

10 Outline 10 Analysis.java Line 19 Line 29 1 // Fig. 4.11: Analysis.java 2 // 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 declarations 10 int passes = 0; // number of passes 11 int failures = 0; // number of failures 12 int studentCounter = 1; // student counter 13 int result; // one exam result 14 15 String input; // user-entered value 16 String output; // output string 17 18 // process 10 students using counter-controlled loop 19 while ( studentCounter <= 10 ) { 20 21 // prompt user for input and obtain value from user 22 input = JOptionPane.showInputDialog( 23 "Enter result (1 = pass, 2 = fail)" ); 24 25 // convert result to int 26 result = Integer.parseInt( input ); 27 28 // if result 1, increment passes; if...else nested in while 29 if ( result == 1 ) 30 passes = passes + 1; Loop until student counter is greater than 10 Nested control structure

11 Outline 11 Analysis.java 31 32 else // if result not 1, increment failures 33 failures = failures + 1; 34 35 // increment studentCounter so loop eventually terminates 36 studentCounter = studentCounter + 1; 37 38 } // end while 39 40 // termination phase; prepare and display results 41 output = "Passed: " + passes + "\nFailed: " + failures; 42 43 // determine whether more than 8 students passed 44 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 application 52 53 } // end main 54 55 } // end class Analysis

12 12 Assignment Operators c = c + 3 –can be written as c += 3

13 13

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

16 Outline 16 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 6 15 16 System.out.println(); // skip a line 17 18 // 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 6 23 24 } // end main 25 26 } // end class Increment 556 566556 566 Line 13 postincrements c Line 21 preincrements c

17 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 18

19 Outline 19 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 13 14 int counter = 1; // initialization 15 16 while ( counter <= 10 ) { // repetition condition 17 g.drawLine( 10, 10, 250, counter * 10 ); 18 ++counter; // increment 19 20 } // end while 21 22 } // end method paint 23 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

20 Outline 20 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 13 14 // 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 ); 18 19 } // end method paint 20 21 } // end class ForCounter Condition tests for counter ’s final value Control-variable name is counter Control-variable initial value is 1 Increment for counter

21 Outline 21 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 10 11 // total even integers from 2 through 100 12 for ( int number = 2; number <= 100; number += 2 ) 13 total += number; 14 15 // display results 16 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 application 21 22 } // end main 23 24 } // end class Sum increment number by 2 each iteration

22 Outline 22 Interest.java Lines 13-15 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 { 10 11 public static void main( String args[] ) 12 { 13 double amount; // amount on deposit at end of each year 14 double principal = 1000.0; // initial amount before interest 15 double rate = 0.05; // interest rate 16 17 // create NumberFormat for currency in US dollar format 18 NumberFormat moneyFormat = 19 NumberFormat.getCurrencyInstance( Locale.US ); 20 21 // create JTextArea to display output 22 JTextArea outputTextArea = new JTextArea(); 23 24 // 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 ($)

23 Outline 23 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 results 40 JOptionPane.showMessageDialog( null, outputTextArea, 41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); 42 43 System.exit( 0 ); // terminate the application 44 45 } // end main 46 47 } // end class Interest Calculate amount with for statement

24 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

25 Outline 25 DoWhileTest.jav a Lines 16-20 1 // 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 13 14 int counter = 1; // initialize counter 15 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 paint 23 24 } // end class DoWhileTest Oval is drawn before testing counter ’s final value

26 26 switch Multiple-Selection Statement switch statement –Used for multiple selections

27 Outline 27 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 14 15 // 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" ); 20 21 choice = Integer.parseInt( input ); // convert input to int 22 23 } // end method init 24 25 // draw shapes on applet's background 26 public void paint( Graphics g ) 27 { 28 super.paint( g ); // call paint method inherited from JApplet 29 30 for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) 31 Get user’s input in JApplet

28 Outline 28 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 entered 49 g.drawString( "Invalid value entered", 50 10, 20 + i * 15 ); 51 52 } // end switch 53 54 } // end for 55 56 } // end method paint 57 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

29 Outline 29 SwitchTest.java

30 Outline 30 SwitchTest.java

31 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 ] case b case z [ false ]

32 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

33 Outline 33 BreakTest.java Line 12 Lines 14-15 1 // 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; 11 12 for ( count = 1; count <= 10; count++ ) { // loop 10 times 13 14 if ( count == 5 ) // if count is 5, 15 break; // terminate loop 16 17 output += count + " "; 18 19 } // end for 20 21 output += "\nBroke out of loop at count = " + count; 22 JOptionPane.showMessageDialog( null, output ); 23 24 System.exit( 0 ); // terminate application 25 26 } // end main 27 28 } // end class BreakTest Loop 10 times exit for structure ( break ) when count equals 5

34 Outline 34 ContinueTest.ja va Line 11 Lines 13-14 1 // 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 = ""; 10 11 for ( int count = 1; count <= 10; count++ ) { // loop 10 times 12 13 if ( count == 5 ) // if count is 5, 14 continue; // skip remaining code in loop 15 16 output += count + " "; 17 18 } // end for 19 20 output += "\nUsed continue to skip printing 5"; 21 JOptionPane.showMessageDialog( null, output ); 22 23 System.exit( 0 ); // terminate application 24 25 } // end main 26 27 } // end class ContinueTest Loop 10 timesSkip line 16 and proceed to line 11 when count equals 5

35 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)


Download ppt "1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators."

Similar presentations


Ads by Google