Presentation is loading. Please wait.

Presentation is loading. Please wait.

Alice in Action with Java Chapter 10 Flow Control in Java.

Similar presentations


Presentation on theme: "Alice in Action with Java Chapter 10 Flow Control in Java."— Presentation transcript:

1 Alice in Action with Java Chapter 10 Flow Control in Java

2 Alice in Action with Java2 Flow Control In Java Purpose of using selective and repetitive execution –Implement methods that produce complex behaviors Selective flow control statements: if and switch Repetitive flow control statements: while, for, do

3 Alice in Action with Java3 Introductory Example: pH Background for the use of pH values –pH: measures the acidity of a solution –pH scale of values: 0 – 14 –Labels for ranges in pH scale: acidic, neutral, alkaline Main elements in a user story built around pH values –pH values of water samples have been recorded –Given pH values of samples, provide correct labels Divide the problem into two subproblems –Build a class to model pH values and operations –Write a program that uses the class to label samples

4 Alice in Action with Java4 Subproblem 1: A PH Class The PH class needs a private instance variable –double type variable is named myValue –myValue will be initialized by a constructor PH constructor –Takes an argument that sets myValue –If pH argument is invalid, an error message displays –Otherwise, pH argument is assigned to myValue The label() method –Returns error message if value is outside range –Otherwise, returns one of three labels

5 Alice in Action with Java5 Subproblem 1: A PH Class (continued)

6 Alice in Action with Java6 Subproblem 2: Processing Multiple pH Values Objective: display labels for sequence of pH values Pseudocode for PhLabeler program –Set the boolean variable named “done” to false –While NOT done: Prompt the user to enter a pH value (-1 to quit) Read ph from the keyboard If ph < the minimum pH value: set done to true ; Else: display phLabel(ph) Observation: if statement nested in a while loop

7 Alice in Action with Java7 Subproblem 2: Processing Multiple pH Values (continued)

8 Alice in Action with Java8 Selective Execution Directing flow based on the value of a condition Two statements that provide selective execution –if statement: general-purpose selection structure –switch statement: multi-branch selection structure

9 Alice in Action with Java9 Java’s if Statement General-purpose selection structure Selects from one or more groups of statements The else portion of the if statement is optional One-branch if : envisioned as branching flow Two-branch if : flow follows one of two branches

10 Alice in Action with Java10 Java’s if Statement (continued)

11 Alice in Action with Java11 Java’s if Statement (continued)

12 Alice in Action with Java12 Java’s if Statement (continued) Pattern for Java’s if statement: if(Condition)Statement 1 [else Statement 2 ] –Condition : any boolean expression –Statement i : set of Java statements within { } –Brackets are optional if only one statement is in path Multi-branch if statements –Flow can move along multiple paths –Nest additional if statements in the else clause

13 Alice in Action with Java13 Java’s if Statement (continued)

14 Alice in Action with Java14 Java’s switch Statement Objective: create a PetLicense class Instance variables used in PetLicense class –char type named myCode stores license code –double type named myFee stores license fee Constructor for a PetLicense object –Takes a single char type argument –Uses multi-branch if to select appropriate fee –If data is valid, instance variables are initialized –If data is invalid, an error message is displayed switch : concise alternative to the multi-branch if

15 Alice in Action with Java15 Java’s switch Statement (continued) Pattern for Java’s switch statement switch(IntegerCompatibleExpression){ CaseList 1 StatementList 1... CaseList N StatementList N default: StatementList N+1 } –The condition is an integer-compatible expression –Each case corresponds to a literal value –The use of default statement optional –Use of break statement below a case is recommended PetLicense class meets criteria for use of switch

16 Alice in Action with Java16 Java’s switch Statement (continued)

17 Alice in Action with Java17 Java’s switch Statement (continued)

18 Alice in Action with Java18 Java’s switch Statement (continued) One switch statement can be nested within another A nested switch statement is used in TShirt class TShirt constructor –Takes on String argument named size –myPrice for standard sizes set in cases ‘ S ’, ‘ M ’, ‘ L ’ –myPrice for ‘ XS ’and ‘ XL ’ are set in case ’ X ’ –Case ’ X ’ includes a nested switch statement Other methods in TShirt class –A method to return mySize and one to return myPrice –toString() returns String value of data members

19 Alice in Action with Java19 Java’s switch Statement (continued)

20 Alice in Action with Java20 Repetitive Execution Program execution flows sequentially by default if and switch perform statements selectively Repetitive execution: control flows in loops Three repetition statements: while, for, and do

21 Alice in Action with Java21 Java’s while Statement Used for processing a series of values Input loops: read and process a series of values Sentinel-controlled input loops –Utilize a sentinel (invalid value) to falsify a condition Problem: extract the initials in a name Members implemented in the Initials class –Instance variables called myName and myInitials –Constructor to initialize the instance variables –Methods to return myName and myInitials

22 Alice in Action with Java22 Java’s while Statement (continued) StringTokenizer class : used to split String s Overview of the Initials class constructor –String argument ( name ) is passed to constructor –Instance variables are initialized –StringTokenizer object called names is initialized –names and while loop are used to extract initials General pattern for Java’s while statement while(Condition)Statement –Statement comprises one or more statements –Curly braces ({ }) required with multiple statements

23 Alice in Action with Java23 Java’s while Statement (continued)

24 Alice in Action with Java24 Java’s while Statement (continued)

25 Alice in Action with Java25 Java’s for Statement Repetition structure for solving counting problems Counting input loop –Simpler design than the sentinel-controlled input loop –Provides repetition when number of inputs is fixed Illustration: computing the city’s air pollution index –A for loop counts from 1 to NUM_READINGS –Each iteration gets a reading and adds it to sum –After loop terminates, index is computed and output Java’s for loop is very flexible –Example: the Java for loop can count down

26 Alice in Action with Java26 Java’s for Statement (continued)

27 Alice in Action with Java27 Java’s for Statement (continued) Overview of NinetyNineBottlesSong program –for loop in constructor counts down from 99 to 0 –Each iteration of the loop adds a verse to myLyrics –main() method constructs and displays the song Plotting a function of the form y = f(x) –for loop iterates through x values and computes f(x) SineWaves class for plotting a sine function –SineWaves should be compiled with Plotter class –Two methods use for loops to plot the sine waves Range of values and increment amounts differ

28 Alice in Action with Java28 Java’s for Statement (continued)

29 Alice in Action with Java29 Java’s for Statement (continued)

30 Alice in Action with Java30 Java’s for Statement (continued)

31 Alice in Action with Java31 Java’s for Statement (continued)

32 Alice in Action with Java32 Java’s for Statement (continued) TextGraphics class illustrates nested for loops Understanding drawBox() in TextGraphics class –Method takes two arguments for height and width –Outer for loop counts the rows (builds the height) –Inner for loop prints asterisk symbol through width General pattern for Java’s for loop for (InitialExpr; Condition; ChangeExpr) Statement –Curly braces ({ }) required with multiple statements –Scope of loop control variable goes to end of loop only

33 Alice in Action with Java33 Java’s for Statement (continued)

34 Alice in Action with Java34 Java’s for Statement (continued)

35 Alice in Action with Java35 Java’s do Statement Pattern for Java’s do statement: do Statement while(Condition); –Loop provides one-trip behavior with posttest condition –You must type a semicolon after the condition Overview of the GuessingGame class –Generates pseudo-random number between 1 and 100 –Retrieves input from user until the number is guessed –Critical logic: multi-branch if nested in a do loop

36 Alice in Action with Java36 Java’s do Statement (continued)

37 Alice in Action with Java37 Java’s do Statement (continued)

38 Alice in Action with Java38 Java’s do Statement (continued) Query-controlled input loop –A loop that terminates when user enters specific value Overview of the GameController class –Utilizes GuessingGame object –Repeats game using query-controlled do loop Default constructor –Constructor provided by Java –Used when a class does not include instance variables GameController utilizes a default constructor

39 Alice in Action with Java39 Java’s do Statement (continued)

40 Alice in Action with Java40 Choosing the Right Loop Solving a problem with fixed counting –Recommendation: use the for loop Solving a problem without fixed counting –If one-trip behavior is needed, use a do loop –If zero-trip behavior is needed, use a while loop Using guidelines to choose loop for Initials –Cannot formulate problem as a counting type Number of words in a name not known in advance –Zero-trip behavior is needed, as name might be null –Result of analysis: while loop is selected

41 Alice in Action with Java41 Choosing the Right Loop (continued)

42 Alice in Action with Java42 Example: The Chaos Game Overview of the ChaosGame class –Uses the algorithm for generating a Sierpinski Triangle –drawVertices() plots vertices of outer triangle –drawPoints() plots the vertices of the inner triangles switch statement is nested in a for loop New point generated and plotted with each iteration –More points to interpolate leads to better resolution Observations –Structure emerges from seemingly random behavior –Computers quickly help users visualize patterns in data

43 Alice in Action with Java43 Example: The Chaos Game (continued)

44 Alice in Action with Java44 Example: The Chaos Game (continued)

45 Alice in Action with Java45 Example: The Chaos Game (continued)


Download ppt "Alice in Action with Java Chapter 10 Flow Control in Java."

Similar presentations


Ads by Google