1 / 42

TA Hours

TA Hours. TA hours have been very busy in the last few days, especially before a project is due Have been busiest between 8:00pm and 12:00am

mikaia
Télécharger la présentation

TA Hours

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. TA Hours • TA hours have been very busy in the last few days, especially before a project is due • Have been busiest between 8:00pm and 12:00am • Hours start at 4:00pm on weekdays, 12:00pm on Saturdays, and 1:00pm on Sundays – go early and save yourself the trouble of waiting in line for hours! • To save both the TAs time and yours, think out your problems before going to see a TA • If there is an error in one of your programs, you must first try to find it and fix it yourself. Use: • Printlines • Hand Simulation • Java Docs • Online TA • Remember: You must wait for an hour before signing up again for TA help! Making Decisions Loops

  2. MAKING DECISIONS Choosing From Many Alternatives switch statements M&M’s example break statements Making Decisions October 15, 2013

  3. If... If... If... What if we want lots of mutually exclusive conditional statements? For maximum generality, Java recognizes the if-else if-else if... construction, with an arbitrary number of else ifs: if (condition_1) { /* body_1 */ } else if (condition_2) { /* body_2 */ } else if (condition_3) { /* body_3 */ } else if (condition_4) { /* body_4 */ } ... else { /* body_n */ } In English, this means if condition_1, execute body_1 otherwise, if condition_2, execute body_2 otherwise, if condition_3, execute body_3 otherwise, if condition_4, execute body_4 . . . otherwise, execute body_n If all we want to do is something different for each value of a simple variable (e.g, age) can’t we do something simpler? Yes! We can use a switch statement! Making Decisions October 15, 2013

  4. switch Statement switch is used to choose among more than two mutually exclusive choices, based on values of a variable. Very special form of general if else-if … switch is like vending machine. When coins are deposited into machine they fall into a ramp with holes for each different type of coin. Smallest slot is for dimes; largest for quarters. 25 5 10 Making Decisions October 15, 2013

  5. switch Statement: Selector switch can pick out one action from among many using a simple key called a selector Selectors cannot be references, fractional numbers, or other complex data types. Of the types we have encountered so far, selectors can be ints, shorts, bytes, or longs. The value of a selector determines the action to be taken. Each possible value for a selector should result in one action or set of actions (one block of code executed). Sometimes a selector does not cover all cases. Use default value to specify what action(s) should be performed when a selector does not fit any other values listed. Making Decisions October 15, 2013

  6. switch: The Flow Chart Much like specialized if-else-if that tests mutually exclusive values of single variable Previous Statements Determine the value of the selector selector = value 1 selector = value n default Execute statement 1 Execute statement n Execute statement n+1 Execute the rest of the program … … Making Decisions October 15, 2013

  7. switch Example: M&M’s Let’s make a factory object that produces M&M’s using a switch statement! Factory is a generalization of a simple constructor to create instances. We want to make a bunch of M&M’s M&M’s come in different colors M&M colors are chosen by some weighted probability distribution more reds, oranges, and browns fewer greens, yellows, and blues Factory specification: Get a random value. Based on the random value, create an M&M of one of the six possible colors. The color of the M&M created should be based on a weighted probability distribution. Return the M&M. Making Decisions October 15, 2013

  8. Designing M&M Factory Use a switch statement to weight probability of getting each color by having multiple values of selector assigned to a single statement body that generates a more likely outcome can “group” cases together - only write one statement body We’ll use the static method Math.random()for some randomness: returns a random double between 0.0 (inclusive) and 1.0 (exclusive); simply multiply by desired range static means we can call this method without actually instantiating Math Remember to castthe resulting number so you get an int (if needed – we do for selector) _randomInt = (int)(Math.random()*10); Let’s see some code... Making Decisions October 15, 2013

  9. M&M’s “First (Incorrect) Solution” Version If 2 is our randomly generated number, what color is our M&M? Note: an instance of class MnM is constructed with a java.awt.Coloras a parameter public class MnMFactory { // constructor elided public MnMgetMnM() { // get a random number to serve as the selector int rand = (int)(Math.random()*10); MnMmnm = null; // not yet created switch (rand) { case 0: case 1: mnm = new MnM(java.awt.Color.PURPLE); // red is the most popular color, hence // a red MnM will be created in three cases case 2: case 3: case 4: mnm = new MnM(java.awt.Color.RED); // code for cases 5, 6, and 7 elided // they are green, blue, yellow respectively default:// a brown color mnm = new MnM(new java.awt.Color(150,100,0)); } return mnm; } } // end of class Making Decisions October 15, 2013

  10. Oh, give me a break But there’s a problem with that code . . . If nothing alters the flow of control, switch statements will “fall through” to the next case i.e., all case statements after any case that matches the selector will be executed! In our example, nothing alters flow of control so, if rand is 0 or 1, code under all cases will be executed likewise, if rand is 2, 3 or 4, the code for cases 2, 3, 4, 5, 6, as well as default case will be executed Remember, we only want one M&M per match! Must have way to stop case from falling through: break out of switch statement Making Decisions October 15, 2013

  11. M&M Factory Method Now, what happens when 3 is selected? How about 4? 5? // ... code elided to save space int rand = (int)(Math.random()*10); MnMmnm = null; // not created yet switch (rand) { case 0: case 1: mnm = new MnM(java.awt.Color.PURPLE); break; case 2: case 3: case 4: mnm = new MnM(java.awt.Color.RED); break; case 5: mnm = new MnM(java.awt.Color.GREEN); break; // cases 6 and 7 elided. case 6 creates a blue // MnM and case 7 creates a yellow MnM. default: // 20% chance of creating brown mnm = new MnM(new java.awt.Color(150, 100, 0)); break; } return mnm; // ... code elided to save space Making Decisions October 15, 2013

  12. Amendment to Previous Diagrams Previous Statements Determine the value of the selector selector = value 1 selector = value n default Execute statement 1 break; Execute statement n break; Execute statement default break; Execute the rest of the program … … Making Decisions October 15, 2013

  13. LOOPS “Life is just one damn thing after another.” – Mark Twain “Life isn’t just one damn thing after another...it’s the same damn thing over and over and over again.” – Edna St. Vincent Millay Loops October 15, 2013

  14. Turtle (courtesy of Logo) • Before we see loops, we need some tools • Turtle: will draw on the screen for us; based on Seymour Papert’s Logo, a language for beginners* • Geometric Patterns: instructions for turtle • Turtles know where they are and what direction they are facing • Turtles draw lines behind them as they move around the screen • Now let’s look at Turtle’s public interface *See his Mindstorms, a provocative book on how kids “learn by doing,” and also the instrumented Legos, Mindstorms Loops October 15, 2013

  15. Turtle’s Public Interface (1 of 2) • TAs have written a Turtle class: public class Turtle extends gfx.Shape { /* instance variables elided */ /* constructor for Turtle takes the panel where the turtle “lives” as parameter to set up an association */ public Turtle(DrawingPanel panel) { // some code here, including storing panel } /* reset turtle to center of panel */ public void home() { // some code here } /* turn right a specified number of degrees */ public void right(int degrees) { // some code here } /* turn left a specified number of degrees */ public void left(int degrees) { // some code here } // continued... Loops October 15, 2013

  16. Turtle’s Public Interface (2 of 2) /* move forward a specified distance, drawing a line as turtle moves */ public void forward(int distance) { // some code here } /*move backward a specified distance, drawing a line as turtle moves */ public void back(int distance) { // some code here } /* move turtle to a specified position without drawing a line */ public void setLocation(java.awt.Point loc) { // some code here } /* return turtle’s location */ public java.awt.PointgetLocation() { // some code here } /* return turtle’s drawing panel */ public DrawingPanelgetPanel() { // some code here } } // end of class Turtle Loops October 15, 2013

  17. Drawing with Turtle • Need class to tell Turtle how to draw some basic shapes • First, determine what shapes we want • this lecture: square, random walk • next lecture: recursive spiral, tree, fractal • How will we code it? • create GeometricPatterns class which defines methods for drawing each shape • methods control turtle, so it needs a reference to the instance, _turtle • geometric patterns do not contain a Turtle, so use a standard design pattern of passing a Turtle reference in the constructor and storing that association • Time for some code! public class GeometricPatterns { private Turtle _turtle; // draws each pattern public GeometricPatterns(TurtlenewTurtle){ _turtle = newTurtle; } // methods for each geometric pattern to // follow... } Loops October 15, 2013

  18. A Repetitive Solution • Let’s write the drawSquare method in the GeometricPatterns class • Brute force: write line of code for each side public void drawSquare(intsideLen) { _turtle.forward(sideLen); _turtle.right(90); _turtle.forward(sideLen); _turtle.right(90); _turtle.forward(sideLen); _turtle.right(90); _turtle.forward(sideLen); _turtle.right(90); } • What if we wanted to make more general method that handles pentagons or octagons? • need to call forward and right for each side • cannot fix how many sides we need in generic method • There must be an easier way! Loops October 15, 2013

  19. Looping • Execute a section of code repeatedly • uses booleans (true and false) as loop conditions; when boolean is false, loop condition equals exit condition and loop is terminated • as with conditionals, section of code can be a single line or many lines enclosed in curly braces • section of code executed is typically called loop’s body • Three loop structures in Java • while loop • do while loop • for loop • Differ in relation between body and loop condition, as well as length of execution • some loops execute body and then test condition; others test condition before executing body • some loops run for a predetermined number of iterations, others run for indefinite amount of time • Look at while loops first Loops October 15, 2013

  20. The while loop • Execute while certain condition is true • tests loop condition before executing body • if loop condition is false first time through, the body is not executed at all while (<loop condition>) { <loop body> } • Examples of loop conditions: • numClasses < 6 • peopleStanding <= maxPeople • this.checkAmount() <= acctBalance • this.isSquare() // predicate; returns boolean • Follow the same rules as conditions for if-else statements • Multiple conditions can be combined using logical operators (and, or, not) (numClasses >= 3) && (numClasses <=5) (peopleStanding <= maxPeople) || (maxPeople < 50) Loops October 15, 2013

  21. A while Flowchart • while loops continue while the loop condition is true • Loop condition can be any boolean expression <previous statement> Is <loop condition> TRUE? Yes <loop body> No <rest of program> Loops October 15, 2013

  22. Flow of Control Structure All Flow of Control Structures are 1-In / 1-Out • Benefits of predictable flow of control: • much easier debugging • compiler can optimize much better • Contrast with “spaghetti” code produced by having a go to construct which allows for jumping to another line of code • Go To Statement Considered Harmfulletter by EdsgerDijkstra, published in Communications of the ACM in 1968 • Go-to-less programming called “structured programming” – took a while to get traction <previous statement> One Way In One Way Out <rest of program> Loops October 15, 2013

  23. So Just How Bad is goto? Loops October 15, 2013

  24. Syntax: Random Walk Using while • Method of GeometricPatterns class: • draws random lines while turtle is within its frame public void randomWalk() { DrawingPanelturtlePanel = _turtle.getPanel(); // while _turtle’s position is inside // its frame, move _turtle randomly while (turtlePanel.contains( _turtle.getLocation())) { _turtle.forward ((int)(Math.random()*15)); // cast _turtle.right ((int)(Math.random()*360)); // cast } } • On last step of walk, _turtle will end up moving forward out of panel • the line is clipped by Swing since we don’t explicitly tell it to wrap • no point in continuing to walk outside of the panel Loops October 15, 2013

  25. The do while Loop • do while always executes loop body at least once by switching order of test and body • <loop condition> is boolean expression <previous statement> <loop body> Is <loop condition> TRUE? Yes No <rest of program> Loops October 15, 2013

  26. Example: Another Random Walk • Method of GeometricPatterns class: • draws random lines while turtle is within its panel • starts turtle in center of drawing panel, so first step guaranteed to be within drawing panel public void centeredRandomWalk() { DrawingPanel panel = _turtle.getPanel(); // moves turtle to Frame’s center _turtle.home(); // moves turtle randomly within frame do { _turtle.forward ((int)(Math.random()*15)); _turtle.right ((int)(Math.random()*360)); } while (panel.contains (_turtle.getLocation())); // note semicolon at end of while // statement } Loops October 15, 2013

  27. do while vs. while • In both loops • stops executing body if loop condition is false • must make sure loop condition becomes false by some computations to avoid an “infinite loop” • infinite loop means your loop condition will never turn false–i.e., exit condition never occurs (and your program “freezes up”!) • do while • body always executed at least once • loop condition tested at bottom of loop • while • may not execute at all • loop condition tested before body; loop condition variables must be set before loop entry • useful for screening bad data that might cause statements within loop to fail (e.g., while (ref != null) ) • What is the difference between these two? while (_andyIsAway) { _tas.takeADayOff(); } do { _tas.takeADayOff(); } while(_andyIsAway); Body executes before condition is tested Condition tested before body Loops October 15, 2013

  28. for Loops • Most specialized loop construct: typically used to execute loop body a predetermined number of times • while and do while loops can execute body for undetermined number of times; based on boolean for (<init-expr>; <loop condition>; <update>) { <loop body> } • <init-expr> • expression for setting initial value of loop counter (traditionally use single character identifier; e.g., i) • executed at start of loop code, i.e. only once, not for each time through the loop • <loop condition> • trueor false • test involves loop counter to determine if loop should execute • checked at the start of every loop (including the first) • <update>: • expression that modifies loop counter • run at the end of every <loop body>, just before returning to the top of the loop Loops October 15, 2013

  29. drawSquare Revisited • Better way of drawing square than explicitly drawing each side: public void drawSquare(intsideLen) { /* start with integer i initialized to 0; execute as long as i < 4; each execution increments i by 1 */ for (inti = 0; i < 4; i++) { _turtle.forward(sideLen); _turtle.right(90); } } Loops October 15, 2013

  30. for Flowchart • for loop has four parts • initialize value of counter • test loop condition • loop body • counter update <init-counter> <update counter> Is <loop condition> TRUE? Yes <loop body> No <rest of program> Loops October 15, 2013

  31. Choosing the Right Loop • for loop is called a definite loop because you can typically predict how many times it will loop. while and do while loops are indefinite loops, as you do not know a priori when they will end. • for loop is typically used for math-related loops like counting finite sums • while loop is good for situations where boolean condition could turn false at any time • do while loop is used in same type of situation as while loop, but when code should execute at least once • When more than one type of loop will solve problem, use the cleanest, simplest one Loops October 15, 2013

  32. Syntax: Nested Loops • Loops, as with if statements, can be nested! • Example: drawFilledSquare public void drawFilledSquare(intsideLen) { // fill in concentric squares for (inti = 0; i < (sideLen / 2); i++) { // drawSquare (slide #29) contains a // loop this.drawSquare(sideLen - (2*i)); /* note we can use loop counter in body but never reset it there! */ // position turtle for next iteration _turtle.right(90); _turtle.forward(1); _turtle.left(90); _turtle.forward(1); } } • What does this do? Note: We are dividing sideLen by 2 in order to guarantee that each “inner square” that is drawn by drawSquare(…) is exactly one unit away on either side from the square immediately “outside” of it (hence, one + one = two). Loops October 15, 2013

  33. Syntax for Nested Loops Explained • Turtle is represented by • What is outer loop doing? • first draws outer square • then the last 4 lines move turtle right and up 1 unit • drawFilledSquare draws concentric squares; each individual square is drawn using the nested loop Turtle starts upright Rotate 90 degrees right Move forward 1 unit Rotate 90 degrees left Move forward 1 unit Loops October 15, 2013

  34. Decrementing Counter • We can count backwards in our loop too • just change counter update expression • in fact, we can update however we want public void countDownSeconds() { /* change counter to decrement, and change the loop condition accordingly */ for (inti = 3; i > 0; i--) { timer.display(i); // hide a finger } } • for loops end in one of two ways • when counter value equals limit (for < or >) • when counter value “goes past” limit (for <= or >=) • thus, countDownSeconds() would display 4 seconds if we used i >= 0 (not a good idea because the movie should play on the 0th second) • Beware of such “off-by-one” errors! Loops October 15, 2013

  35. break • break causes immediate exit from a flow-of-control structure (e.g., while, do while,for,switch ) • Example: // We’d like to eat 10 cookies (they’re small!) for (inti = 0; i < 10; i++) { if(_cookieJar.getNumberOfCookies() = = 0 ) { break;// If there are no cookies left, // we should break out of the loop // because we can’t eat any more! } // eating a cookie means getNumberOfCookies() // returns a value 1 less than before this.eatACookie(); // We know there are some // left } // Execution continues here after loop is done // or after break statement is executed • Execution continues with first line of code after structure • There are other ways to do this loop… Loops October 15, 2013

  36. continue • When used in a while, for, or do while structure, continue skips remaining statements in body of that structure and proceeds with the next iteration of loop • useful if there is list of data that you are looping over and you want to skip processing of data that is somehow “not allowed” • Example: // We’d like to try on shirts that hang on a // rack for (inti = 0; i < 20; i++) { if(!rack.isShirtOnHanger(i)) { // If there’s no shirt on the current // hanger, skip to the next iteration continue; } // Only do this if there’s a shirt on the // hanger Shirt shirtToTry = rack.shirtOnHanger(i);// get the shirt this.tryOnShirt(shirtToTry); // try on shirt } // more code here • In while and do while structures, execution continues by evaluating loop-continuation condition • In for structure, execution continues by incrementing counter and then evaluating loop condition Loops October 15, 2013

  37. Boolean Flags • A boolean flag is a boolean variable that denotes a condition (e.g., isDone, isWorking, isAvailable) • set in one place, tested in another • similar to boolean methods, often starts with “is” or “has” by convention • Boolean flags can also be used as the loop condition • Example (implementing a for loop, using while): booleanisDone = false; inti = 0; while (!isDone) { i++; if (i == 5) { isDone = true; } } • Notice that boolean flag is set within loop • in previous slides, all checking was done through delegation (to methods that returned booleans); here we do it ourselves Loops October 15, 2013

  38. Empty Intervals • Example scenario: We want to keep a running sum of a sequence of numbers • What happens if we try to add integers in this loop? public int sum() { inttempSum = 0; for (inti = 1; i < 1; i++) { tempSum += i; } return tempSum; } • Answer: body of loop is not executed • Why? • boolean is false for initial value of counter • Correct example: /* This method sums all numbers from 1 up to and including 10 */ public int sum() { inttempSum = 0; for (inti = 1; i <= 10; i++) { tempSum += i; } return tempSum; } Loops October 15, 2013

  39. Off-by-one Errors • Occur when loop executes one too many or one too few times • Example: Add even integers from 2 to some number, inclusive ... count = 2; result = 0; while (count < number) { result += count; count += 2; } • Produces incorrect result if number is assigned an even value. Values from 2 to number–2 will be added (i.e., number is excluded) • Should be: while (count <= number) { ... } • Now, the value of number is included in the summation Loops October 15, 2013

  40. Syntax: Other Loop Errors • Make sure test variables have proper values before loop is entered ... product = 0; do { product *= 2; } while (product < 100); /* What will happen here? */ • Make sure tests check proper conditions ... for (inti = 1; i != 100; i += 2) { // do something here } /* Will we ever get here? */ • ALWAYS HAND SIMULATE first, last, and typical cases through a loop to avoid off-by-one or infinite loop errors • the first and last cases of a loop’s execution are called boundary conditions or edge cases • hand simulation doesn’t just apply to loops – use it for everything! Trust us – it saves debugging time! Loops October 15, 2013

  41. Which Loop to Use? • You want to bake a pie for each of your twelve friends • Your job is to stand at the end of the bowling alley, and pick up all the pins, one by one, that have been knocked over • Ask a question. Keep asking while the answer is incorrect. • Sleep until your clock reads 7:00AM or later Loops October 15, 2013

  42. Announcements • Textbook Reading Assignment • 12.1 through 12.4 • Cartoon is due this week: • Early: Thursday at 11:59pm • On-time: Saturday, October 19, 2013, at 11:59pm • Late: Monday, October 21, 2013, at 10:00pm • Go crazy with your Cartoons! Best Cartoons will be showcased in class  • NOTE: Many of you have had questions about shapes not appearing on the screen. Make sure you are: • Setting the shape’s visibility to true • Giving the shape a size • Painting the shape • Etc. • Doodle Jump (yay!) goes out this Thursday! DQs are due Saturday, October 26, 2013 at 10:00pm. Due dates for programming part: • Early: Friday, November 01, 2013, at 11:59pm • On-time: Sunday, November 03, 2013, at 11:59pm • Late: Tuesday, November 05, 2013, at 11:59pm • Remember to complete Lab 5 (Pseudocode) this week. • New Concept of the Week is out! Loops October 15, 2013

More Related