Alice in Action with Java Chapter 4 Flow Control.

Slides:



Advertisements
Similar presentations
Decision Structures Chapter 4. Chapter 4 Objectives To understand: o What values can be stored in a Boolean variable o What sequence structures are and.
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Alice: A Visual Introduction to Programming First Edition.
Events Chapter 7. Interactivity The real world is interactive User determines order of actions instead of programmer.
Princess & Dragon Part 2: Teaching a Dragon to Fly—Methods & Properties By Elizabeth Liang under the direction of Professor Susan Rodger Duke University.
Events Chapter 7. Interactive Real world is interactive User determines order of actions instead of programmer.
Repetition Structures
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Alice in Action with Java
Alice Variables Pepper. Set to Java look Edit / preferences restart.
Alice in Action with Java
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Alice in Action with Java Chapter 10 Flow Control in Java.
Alice in Action with Java
Chapter 2: Algorithm Discovery and Design
Chapter 2: Algorithm Discovery and Design
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Calvin and Hobbes Teach Properties and Functions Created by Daniel MacDonald under the direction of Professor Susan Rodger Duke University June 2013.
Fundamentals of Python: From First Programs Through Data Structures
CSC103: Introduction to Computer and Programming
01-Intro-Object-Oriented-Prog-Alice1 Barb Ericson Georgia Institute of Technology Aug 2009 Introduction to Object-Oriented Programming in Alice.
Variables and Functions Chapter Variables Named storage location in computer’s memory Programs may need to store data when running o Stored in.
Fundamentals of Python: First Programs
Programming Logic Program Design. Objectives Steps in program development Algorithms and Pseudocode Data Activity: Alice program.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Branching and Looping Examples, cont’d. Remember the generic triple jump world…
Chapter 5: Control Structures II (Repetition)
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Programming in Java Unit 4. Learning outcome:  LO2: Be able to design Java solutions  LO3: Be able to implement Java solutions Assessment criteria:
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
By Melissa Dalis Professor Susan Rodger Duke University June 2011 Multiplication Table.
© 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.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Flow Control: Repetition with For Loops (Alice In Action, Ch 4) Slides Credit: Joel Adams, Alice in Action CS 120 Lecture September 2012.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Flow Control: boolean expressions, “if” selection statements (Alice In Action, Ch 4) Slides Credit: Joel Adams, Alice in Action CS 120 Lecture September.
Mathematical Expressions, Conditional Statements, Control Structures
Bunny Eat Broccoli Repetition – Simple loops and Conditional loops Susan Rodger Duke University July 2011.
JavaScript, Fourth Edition
Alice in Action with Java Chapter 5 Lists and Arrays.
Variables (Alice In Action, Ch 3) Slides Credit: Joel Adams, Alice in Action CS120 Lecture 04 7 September 2012.
Copyright 2008 Wanda Dann, Steve Cooper, Don Slater Alice Workshop Functions, Loops, and Parameters.
Repetition Structures Chapter 5 Part The While Instruction  Combines Loop and the condition that is also used in If/else statements  The loop.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Events Programming with Alice and Java First Edition by John Lewis.
Methods (part 2) Alice In Action, Ch 2 Slides Credit: Joel Adams, Alice in Action CS 120 Lecture 03 4 September 2012.
Flow Control: Repetition with While Loops (Alice In Action, Ch 4) Slides Credit: Joel Adams, Alice in Action CS 120 Lecture September 2012.
Alice in Action with Java Chapter 4 Flow Control.
Methods (part 1) Alice In Action, Ch 2 Slides Credit: Joel Adams, Alice in Action CS120 Lecture August 2012.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4-1 Lecture Objectives To understand: –what values can be stored in a Boolean.
Princess & Dragon Part 3: A Knight Comes Riding In—Cameras & Events By Elizabeth Liang under the direction of Professor Susan Rodger Duke University June.
An Introduction to Programming Using Alice 2.2, Second Edition Chapter 7 Recursive Algorithms.
Alice in Action with Java Chapter 2 Methods. Alice in Action with Java2 Objectives Build world-level methods to help organize a story into scenes and.
Chapter 3: Decisions and Loops
Python: Control Structures
Chapter 5: Control Structures II
Repetition Control Structures
Programming Logic Alice.
Alice in Action with Java
Learning Java with Alice 3.0 Game Design Kathy Bierscheid
Making Decisions in a Program
Outline Altering flow of control Boolean expressions
Alice in Action with Java
Parameters and World-level methods
An Introduction to Programming Using Alice 2.2, Second Edition
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Alice in Action with Java Chapter 4 Flow Control

Alice in Action with Java2 Objectives Use the Boolean type and its basic operations Use the if statement to perform some statements while skipping others Use the for and while statements to perform (other) statements more than once Use Boolean variables and functions to control if and while statements Use the wait() message to temporarily suspend program execution

Alice in Action with Java3 Flow Control Flow: sequence of steps for performing a user story Flow control statement: structure for managing flow Flow control statements used in previous chapters –doInOrder : produces a sequential execution –doTogether : produces a parallel execution Control statements introduced in the current chapter –if : directs program flow along one of two paths –for : directs flow into a fixed number of loops –while : directs flow into an arbitrary number of loops

Alice in Action with Java4 Flow Control (continued)

Alice in Action with Java5 The Boolean Type A basic Alice type used to define Boolean variables A Boolean variable holds a value of true or false Other basic types: Number and Object Condition (Boolean expression) –Produces a value of true or false –Basis for decision-making in programs

Alice in Action with Java6 Boolean Functions Return a value of true or false Can act as a condition in an if or while statement Many refer to an object’s bounding box Example: obj.isBehind(obj2) –true, if obj ’s position is beyond obj2 ’s rear edge –false, otherwise

Alice in Action with Java7 Boolean Variables Used to store a value of true or false Can be used in condition for if or while statement How to create a Boolean variable –Click create new variable (or parameter ) button –Specify Boolean as variable (or parameter) type

Alice in Action with Java8 Relational Operators Produce true or false values Six relational operators: ==, !=,, >= Located in functions pane of world ’s details area Most often used to compare Number values Example: hoursWorked > 40 –hoursWorked is a Number variable –true when more than 40 hours have been worked

Alice in Action with Java9 Relational Operators (continued)

Alice in Action with Java10 Boolean Operators Used to modify or combine relational operations Three Boolean operators: AND, OR, NOT Located in functions pane of world ’s details area Example: age > 12 && age < 20 –age is a Number variable –Teen number compared to condition returns true

Alice in Action with Java11 Boolean Operators (continued)

Alice in Action with Java12 Introducing Selective Flow Control Summary of a scene with a princess and a dragon –Princess meets a mute dragon and asks questions –Dragon shakes its head to respond yes or no Objective: write a shakeHead() method Requirements for shakeHead() –Parameter: yesOrNo, a String –If yesOrNo == “yes”, dragon shakes head up and down –If yesOrNo == “no”, dragon shakes head sideways Use an if statement to produce conditional behavior –The if control structure is at bottom of editing area

Alice in Action with Java13 Introducing Selective Flow Control (continued)

Alice in Action with Java14 if Statement Mechanics Value of a condition determines direction of flow Structure of an if statement: –if (Condition ) { Statements 1 } else { Statements 2 } if statement behavior is also called selective flow –If Condition is true, Statements 1 are selected –If Condition is false, Statements 2 are selected

Alice in Action with Java15 if Statement Mechanics (continued)

Alice in Action with Java16 Building if Statement Conditions Coding the condition of the if statement –Click on the yesOrNo parameter –Drag parameter into the editing area –Drop the parameter onto the condition’s placeholder –Choose other and then type “yes” Overview for coding the remainder of shakeHead() –Add headMovement variable for amount of turn –Add turn() statements for up and down motion –Add turn() statements for sideways motion

Alice in Action with Java17 Building if Statement Conditions (continued)

Alice in Action with Java18 Building if Statement Conditions (continued) Building a scene method that uses shakeHead() –princess greets dragon using a say() message –princess asks four questions –shakeHead() is called in response to each question Click the Play button to test the program

Alice in Action with Java19 Building if Statement Conditions (continued)

Alice in Action with Java20 Building if Statement Conditions (continued)

Alice in Action with Java21 The wait() Statement Pauses a program for specified number of seconds Form of wait() statement: wait(numSecs); Use of wait() scene with dragon and princess –Inserted between princess’s first and second lines

Alice in Action with Java22 Validating Parameter Values if statement can be used to guard set of statements –Flow enters only if parameter values are valid Example: check distance value passed to jump() –Check for positive value with condition distance > 0 –Check jump length with distance < MAX_DISTANCE –Combine two conditions with the AND ( && ) operator distance > 0 && distance <= MAX_DISTANCE How to incorporate validating logic using if structures –Place original jump() logic onto true path (outer if ) –Place validating logic in the false path (nested if )

Alice in Action with Java23 Validating Parameter Values (continued)

Alice in Action with Java24 Validating Parameter Values (continued)

Alice in Action with Java25 Validating Parameter Values (continued)

Alice in Action with Java26 Introducing Repetition Refer to flapWings() method from Figure 2-16 Enhancement: use for loop to flap wings numTimes Overview for implementing the enhancement –Open the flapWings() method –Adjust the duration values for the wing movements –Drag loop control to the top of the method and drop –Select numTimes for number of iterations –Drag the doInOrder statement into the for statement

Alice in Action with Java27 Introducing Repetition (continued)

Alice in Action with Java28 Introducing Repetition (continued)

Alice in Action with Java29 Mechanics of the for Statement Repeat statement execution a fixed number of times Example: pass 3 to flapWings() for 3 flaps Structure of the simple for statement –for(int index = 0;index < limit;index++){ Statements } The for statement is also known as a counting loop –First statement in ( ) initializes the index –Second statement in ( ) checks index against limit –Third statement in ( ) increments the index

Alice in Action with Java30 Mechanics of the for Statement (continued)

Alice in Action with Java31 Mechanics of the for Statement (continued) To test a for loop, trace the behavior with values –Statements are executed while index < numTimes –Example: send flapWings(3) to the dragon object Simple version of for lets you modify limit value Purpose of show complicated version button –Change initial value of index and/or update to index –Example: change update to index+=2 Note: neither version of for allows you to count down

Alice in Action with Java32 Mechanics of the for Statement (continued)

Alice in Action with Java33 Mechanics of the for Statement (continued)

Alice in Action with Java34 Nested Loops Three shots enhancing Scene 1 of dragon animation –Dragon flies toward a castle in the countryside –As dragon nears castle, it circles the tower three times –Dragon then descends and lands on the drawbridge One way to build the first shot –Go to go into the Add Objects window –Position the dragon above the castle’s drawbridge –Move dragon up until it is even with the castle’s tower –Drop a dummy and then drag the dragon off-screen –Use setPointOfView() to properly position dragon

Alice in Action with Java35 Nested Loops (continued) One way to build the second shot –Use for statement to control other flying statements Understanding the mechanics of Shot 2 –Outer for controls inner (nested) for in flapWings() –AsSeenBy() attribute revolves dragon around castle –Increase duration of turn() to synchronize moves –Set style to smooth the animation The third shot is discussed in Section 4.4

Alice in Action with Java36 Nested Loops (continued)

Alice in Action with Java37 The while Statement limit value in for loop must be set to a fixed value Circumstance when the for loop is appropriate –Statements are to be executed a fixed number of times Problem: looping when the limit value is unknown Solution: use a while statement

Alice in Action with Java38 Introducing the while Statement Strategy for building third shot of dragon animation –Repeatedly have dragon flap its wings –Move dragon downward while it is above drawbridge Overview for building the third shot –Place doTogether statement in doInOrder statement –Use setPointOfView() to move camera closer –Send flappingWings() message to the dragon –Drag the while statement to the editing area –Drop the while statement below doInOrder –Insert placeholder value into the while condition

Alice in Action with Java39 Introducing the while Statement (continued)

Alice in Action with Java40 Introducing the while Statement (continued) Building the third shot (continued) –Drag dragon’s isAbove() over condition and drop –Add castle.bridge argument to isAbove() –Insert doTogether statement in the while loop –Add move() method to cause dragon to descend –Send another flapWings() message to dragon –Use setPointOfView() to zoom in for a close-up Infinite loop occurs if loop lacks falsifying condition –In third shot, move() eventually terminates loop

Alice in Action with Java41 Introducing the while Statement (continued)

Alice in Action with Java42 Introducing the while Statement (continued)

Alice in Action with Java43 while Statement Mechanics Provides for both definite and indefinite looping Structure of a while loop –while ( Condition ) { Statements } The while loop is more general than the for loop –Flow enters while structure if Condition is true –One statement must eventually falsify Condition

Alice in Action with Java44 while Statement Mechanics (continued)

Alice in Action with Java45 Comparing the for and while Statements while statement can produce any type of repetition for statement is used for fixed number of repetitions Loop selection question to ask: “Am I counting?” –If yes, use a for statement; otherwise, use while Both loops test conditions before flow enters structure Both loops are bypassed if initial condition is false

Alice in Action with Java46 A Second Example Setting up the scene –Use shebuilder to create a soccer player (Jane) –Place soccerBall object in Jane’s hands Writing a dropBounce() method for soccerBall –Move the ball down distanceToGround meters –Change distanceToGround by bounce factor (2/3) –Move ball up reduced distanceToGround meters –Bouncing continues while distanceToGround > 0 Writing a janeDropsBall() method –Send roll() messages to forearms –Send dropAndBounce() message to soccerBall

Alice in Action with Java47 A Second Example (continued)

Alice in Action with Java48 A Second Example (continued)

Alice in Action with Java49 A Second Example (continued)

Alice in Action with Java50 Flow-Control Functions Functions can be defined to answer questions Complex questions are asked by flow-control functions

Alice in Action with Java51 Spirals and the Fibonacci Function User story –Scene 1: girl finds an old book and reads contents –Scene 2: girl uses the map to locate a palm tree –Scene 3: girl follows spiral from tree to treasure site Coding spiral motion in Scene 3 is greatest challenge Many natural spirals are based on Fibonacci numbers Fibonacci numbers (sequence) –Number > 1 is found by adding two preceding numbers –Example: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,... –Spiral inscribed in rectangles built from the sequence

Alice in Action with Java52 Spirals and the Fibonacci Function (continued)

Alice in Action with Java53 Spirals and the Fibonacci Function (continued) Approximating Fibonacci spiral in playScene3() –Have girl move 6 times –Distance of each move equals next Fibonacci number –While moving forward, girl also turns left 1/4 revolution playScene3() requires a fibonacci() function –To be designed and implemented in the next section Save girl as fibonacciGirl for possible reuse

Alice in Action with Java54 Spirals and the Fibonacci Function (continued)

Alice in Action with Java55 The Fibonacci Function Defining the outline of fibonacci() function –Select girl and create a function named fibonacci –Create a Number parameter named n Formula: if n > 1, f(n) = sum of two preceding numbers Designing an algorithm to generate the n th number –Create local variables: result, nextToLast, last –Add if statement to the function –If n == 1 or n == 2, result = 1 –Otherwise calculate n th value using formula in for loop fibonacci() calls in playScene3() specify spiral

Alice in Action with Java56 The Fibonacci Function (continued)

Alice in Action with Java57 Summary Flow control statement: controls the flow of statement execution Condition: Boolean expression producing a true or false value Boolean function: returns true or false value Boolean variable: holds value of true or false Relational operators: ==, !=,, >=

Alice in Action with Java58 Summary (continued) Boolean operators: AND, OR, NOT if statement: directs flow along one of two paths based on evaluation of a condition for statement: repeats execution of a group of statements a fixed number of times while statement: repeats execution of a group of statements an arbitrary number of times wait() statement: a statement that pauses program flow for a specified number of seconds