450 likes | 636 Views
Alice in Action with Java. Chapter 10 Flow Control in Java. 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.
E N D
Alice in Action with Java Chapter 10 Flow Control in Java
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
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
Subproblem 1: A PH Class • The PHclass needs a private instance variable • doubletype variable is named myValue • myValuewill 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
Subproblem 1: A PH Class (continued) Alice in Action with Java
Subproblem 2: Processing Multiple pH Values • Objective: display labels for sequence of pH values • Pseudocode for PhLabeler program • Set the booleanvariable 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
Subproblem 2: Processing Multiple pH Values (continued) Alice in Action with Java
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
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
Java’s if Statement (continued) Alice in Action with Java
Java’s if Statement (continued) Alice in Action with Java
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 ifstatements • Flow can move along multiple paths • Nest additional if statements in the else clause Alice in Action with Java
Java’s if Statement (continued) Alice in Action with Java
Java’s switch Statement • Objective: create a PetLicense class • Instance variables used in PetLicense class • chartype namedmyCode stores license code • doubletype namedmyFee stores license fee • Constructor for a PetLicenseobject • Takes a single chartype 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
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 breakstatement below a case is recommended • PetLicense class meets criteria for use of switch Alice in Action with Java
Java’s switch Statement (continued) Alice in Action with Java
Java’s switch Statement (continued) Alice in Action with Java
Java’s switch Statement (continued) • Oneswitch statement can be nested within another • A nested switch statement is used in TShirt class • TShirt constructor • Takes on String argument named size • myPricefor standard sizes set in cases ‘S’, ‘M’, ‘L’ • myPricefor ‘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
Java’s switch Statement (continued) Alice in Action with Java
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
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 Initialsclass • Instance variables called myName and myInitials • Constructor to initialize the instance variables • Methods to return myName and myInitials Alice in Action with Java
Java’s while Statement (continued) • StringTokenizerclass:used to splitStrings • 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 • Statementcomprises one or more statements • Curly braces ({ }) required with multiple statements Alice in Action with Java
Java’s while Statement (continued) Alice in Action with Java
Java’s while Statement (continued) Alice in Action with Java
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
Java’s for Statement (continued) Alice in Action with Java
Java’s for Statement (continued) • Overview ofNinetyNineBottlesSongprogram • 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
Java’s for Statement (continued) Alice in Action with Java
Java’s for Statement (continued) Alice in Action with Java
Java’s for Statement (continued) Alice in Action with Java
Java’s for Statement (continued) Alice in Action with Java
Java’s for Statement (continued) • TextGraphics class illustrates nested for loops • Understanding drawBox()in TextGraphicsclass • Method takes two arguments for height and width • Outer forloop counts the rows (builds the height) • Inner forloop 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
Java’s for Statement (continued) Alice in Action with Java
Java’s for Statement (continued) Alice in Action with Java
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
Java’s do Statement (continued) Alice in Action with Java
Java’s do Statement (continued) Alice in Action with Java
Java’s do Statement (continued) • Query-controlled input loop • A loop that terminates when user enters specific value • Overview of the GameController class • Utilizes GuessingGameobject • 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
Java’s do Statement (continued) Alice in Action with Java
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
Choosing the Right Loop (continued) Alice in Action with Java
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 • switchstatement is nested in a forloop • 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
Example: The Chaos Game (continued) Alice in Action with Java
Example: The Chaos Game (continued) Alice in Action with Java
Example: The Chaos Game (continued) Alice in Action with Java