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

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Program Design and Development
Chapter 5: Loops and Files.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Alice in Action with Java Chapter 10 Flow Control in Java.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
The switch Statement, DecimalFormat, and Introduction to Looping
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Java Programming: From the Ground Up
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Controlling Function Behavior Sequence, Selection and Repetition.
Flow of Control Part 1: Selection
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Visual Basic Programming
Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an instruction set Three repetition structures: while,
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Repetition Structures.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Calvin College Controlling Behavior The if, switch and for Statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Controlling Behavior The if and for Statements. Function Behavior The behavior of a function is determined by the statements within the function. Statements.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
© 2006 Pearson Education Chapter 3 Part 2 More about Strings and Conditional Statements Loops (for and while) 1.
Controlling Behavior The if and for Statements.
REPETITION CONTROL STRUCTURE
Python: Control Structures
Java Programming: Guided Learning with Early Objects
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to Repetition Structures
Outline Altering flow of control Boolean expressions
Structured Program
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Chapter 5: Control Structures II (Repetition)
Topics Introduction to Repetition Structures
Controlling Behavior The if and for Statements.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Alice in Action with Java Chapter 10 Flow Control in Java

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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