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

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

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

Alice in Action with Java

Chapter 10Flow Control in Java

Alice in Action with Java 2

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

Alice in Action with Java 3

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

Alice in Action with Java 4

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

Alice in Action with Java 5

Subproblem 1: A PH Class (continued)

Alice in Action with Java 6

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

Alice in Action with Java 7

Subproblem 2: Processing Multiple pH Values (continued)

Alice in Action with Java 8

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

Alice in Action with Java 9

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

Alice in Action with Java 10

Java’s if Statement (continued)

Alice in Action with Java 11

Java’s if Statement (continued)

Alice in Action with Java 12

Java’s if Statement (continued)

• Pattern for Java’s if statement: if(Condition)Statement1 [else Statement2]

– Condition: any boolean expression

– Statementi: 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

Alice in Action with Java 13

Java’s if Statement (continued)

Alice in Action with Java 14

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

Alice in Action with Java 15

Java’s switch Statement (continued)

• Pattern for Java’s switch statement switch(IntegerCompatibleExpression){ CaseList1 StatementList1 ... CaseListN StatementListN default: StatementListN+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

Alice in Action with Java 16

Java’s switch Statement (continued)

Alice in Action with Java 17

Java’s switch Statement (continued)

Alice in Action with Java 18

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

Alice in Action with Java 19

Java’s switch Statement (continued)

Alice in Action with Java 20

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

Alice in Action with Java 21

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

Alice in Action with Java 22

Java’s while Statement (continued)

• StringTokenizer class:used to split Strings

• 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

Alice in Action with Java 23

Java’s while Statement (continued)

Alice in Action with Java 24

Java’s while Statement (continued)

Alice in Action with Java 25

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

Alice in Action with Java 26

Java’s for Statement (continued)

Alice in Action with Java 27

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

Alice in Action with Java 28

Java’s for Statement (continued)

Alice in Action with Java 29

Java’s for Statement (continued)

Alice in Action with Java 30

Java’s for Statement (continued)

Alice in Action with Java 31

Java’s for Statement (continued)

Alice in Action with Java 32

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

Alice in Action with Java 33

Java’s for Statement (continued)

Alice in Action with Java 34

Java’s for Statement (continued)

Alice in Action with Java 35

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

Alice in Action with Java 36

Java’s do Statement (continued)

Alice in Action with Java 37

Java’s do Statement (continued)

Alice in Action with Java 38

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

Alice in Action with Java 39

Java’s do Statement (continued)

Alice in Action with Java 40

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

Alice in Action with Java 41

Choosing the Right Loop (continued)

Alice in Action with Java 42

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

Alice in Action with Java 43

Example: The Chaos Game (continued)

Alice in Action with Java 44

Example: The Chaos Game (continued)

Alice in Action with Java 45

Example: The Chaos Game (continued)