1 / 88

Continuation from last time

Continuation from last time. break. break causes immediate exit from a flow-of-control structure (e.g. while , do while , for , switch ) Example:. for ( int i = 0; i < 10; i ++){ if(_ cookieJar.getNumberOfCookies () == 0){

Télécharger la présentation

Continuation from last time

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. Continuation from last time

  2. break • breakcauses immediate exit from a flow-of-control structure (e.g. while, do while, for, switch) • Example: for (inti = 0; i < 10; i++){ if(_cookieJar.getNumberOfCookies() == 0){ break; //If there are no cookies left, we should break out of the loop! } this.eatACookie(); } //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…

  3. continue When used in a while, for, or do while structure, continueskips 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” In whileand do while structures, execution continues by evaluating loop-continuation condition In forstructure, execution continues by incrementing counter and then evaluating loop condition

  4. continue 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

  5. 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 forloop, using while): 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 (not practical) booleanisDone = false; inti = 0; while (!isDone){ i++; if(i == 5){ isDone = true; } }

  6. 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? Answer: body of loop is not executed Why? boolean is false for initial counter value public int sum() { inttempSum = 0; for (inti = 1; i < 1; i++) { tempSum+= i; } return tempSum; }

  7. Correct Example What about this loop? /*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; } It will work!

  8. 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 numberis assigned an even value. Values from 2 to number-2 will be added (i.e. numberis excluded) Should be: Now, the value of number is included in the summation while (count <= number){ ... }

  9. 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? */

  10. Syntax: Other Loop Errors • 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!

  11. Which loop to use? You want to send a candygram to 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 ?

  12. C [0] S [1] C [2] I [3] [4] 0 [5] 1 5 [6] [7] 0 Arrays Uses, Syntax, Multi-Dimensional Arrays, Array Lists, and Generics

  13. Why Use Arrays? (1/2) • Until now, we have used variables that hold references only to single objects • But what if we want to hold lots of data? Many programs need to keep track of hundreds (or hundreds of thousands) of data pieces • Want to hold arbitrary number of objects with single reference • Represents collection of elements • Can send messages to multiple elements much more easily

  14. Why Use Arrays? (2/2) • Arrays are oldest form of composite data structure, first found in FORTRAN (FORmula TRANslator, 1955), first high-level programming language designed by John Backus et al at IBM for number-crunching and still in use today: “FORTRAN is a hardy weed…” • Arrays are the simplest collection - we’ll study linked lists, queues, stacks, trees, and more

  15. Fibonacci Sequence (1/3) • Suppose we want to keep track of the first 20 numbers in the Fibonacci Sequence • sequence begins with zero and one • successive numbers are determined by adding the previous two numbers • third number: add first & second numbers (0+1=1); • fourth number: add second & third numbers (1+1=2); • and so on...

  16. Fibonacci Sequence (2/3) • Beginning of sequence looks like this: 0 1 1 2 3 5 8 13 21 34 55 89 We could do it with instance variables… public class FibSequence { private int _firstNum, _secondNum, _thirdNum, … _twentiethNum; }

  17. Fibonacci Sequence (3/3) • This gets tiresome and is not very flexible • try making a sequence with forty numbers • now try it with a thousand!

  18. Arrays (1/4) • Arrays store a specified, constant number of homogenous (same type) data elements • Simplest homogenous collection • Each element must be same type or subclass of same type (polymorphism) • Arrays are special in Java • provide special syntax to access array elements: _studentArray[index] • neither base type nor class, but Java construct • cannot subclass • only methods are those defined by Objectclass • and we won’t use those… • new to initialize an array (even though it’s not a class!)

  19. Arrays (2/4) • Arrays hold only elements of specified type • When declaring an array, state typeof object that array stores (base type, class, or for max polymorphic flexibility, interface) • If storing class, can put references to instances of only that type (or subtype) into array • Note: you could declare array to be of java.lang.Objecttype to store any instance, but not useful: wouldn’t take advantage of compiler’s type-checking...

  20. Arrays (3/4) • Every array element is an object reference or base type. What real-world objects could we organize with arrays? • floors of buildings • streets in Manhattan • strings representing names of people in a course • Elements are ordered sequentially by numerical index • in mathematics, we refer to related variables by using subscript notation, i.e., A1, A2, A3, ...An • with Java, represent index inside brackets, i.e., array[0], array[1],...array[n-1]

  21. Arrays (4/4) • Arrays store objects in numbered slots • for array of size n, first index is always 0, last index is always n-1 • Common graphical representations of arrays:

  22. Array Examples • The Sunlab Computers • Array size:72 • Array index: node number • Element type: computer Note: This could also be modeled as a 2D array (see slide 26)

  23. Array Examples • Houses on a Neighborhood Street • Array size: 8 • Array index: house number • Element type: house • Note: arrays don’t need to be full (e.g., no house 0, 4, or 7)

  24. Java’s Syntax for Arrays (1/4) Declaration: <type>[]<array-name>; • <type>denotes data type that the array is to hold in each slot: can be class, base type, interface, or even another array (for nested arrays) • Colorable[ ] myColorables; declares a one-dimensional array that holds references to instances of classes that implement Colorable interface • Note: unlike some other programming languages, size of array not specified in declaration, but initialization; • also no reserved word “array” - brackets suffice

  25. Java’s Syntax for Arrays (2/4) Initialization:<array-name> = new <type>[<size>]; • <size>must be an integer value greater than 0; indices will range from 0 to <size> -1 • We use new here, but because arrays are a built-in type in Java, we have special syntax and do not call a constructor. • here we initialize array after declaring it Colorable[] _myColorables; ... //in constructor _myColorables = new Colorable[10]; • note only array is initialized, not elements of array; all references are set to null, 0 for ints, false for booleans, etc. • Alternatively, we can declare and initialize in one statement, just like we can with objects and base types Colorable[] otherColorables = new Colorable[5];

  26. Java’s Syntax for Arrays (3/4) • Accessing individual elements: <array-name>[<index>] • index must be an integer between 0 and (array_size-1) • result is the variable stored at that index • if <index> ≤ size, or < 0, an ArrayIndexOutOfBoundsException is thrown • Additionally, useful to check for uninitialized entries with ref != null --- See slide 45

  27. Java’s Syntax for Arrays (4/4) • Anywhere that you can use a variable or a constant, you can also use an array element. For example, in your ShapePanel: Note: in some other languages, index can run between any two integers (m, n), where m<n • //initialize first element of an array of Colorables to be an Ellipse • myColorables[0] = new EllipseShape(); • //send a message to 3rd element of the array, assuming it is not null • myColorables[2].setColor(java.awt.Color.RED); • //assign fourth element of array to a local variable • Colorable myColorableVar = myColorables[3]; • //pass 5th element of the array as a parameter • _myPaintShop.paintRandomColor(myColorables[4]);

  28. Arrays as Parameters • Can pass in an entire array as parameter by adding array brackets to type of formal parameter • public int sum(int[] numbers){ • //code to compute sum of elements in the int array • }

  29. Arrays as Parameters - length • How do we determine size of array? • could pass in a second parameter, specifying size • arrays have their length as a public property (not a method) • use special “dot” syntax to find out length; here we inquire it, then store it for future use int arrayLength = <array-name>.length; • How might you use length in an actual piece of code? Note common use of forto loop thru all elements of an array • public int sum (int[] numbers){ • int total = 0; • for (int i=0; i< numbers.length; i++){ • total += numbers[i]; • } • return total; • } What if the code read i<=numbers.length? “off-by-one” error - go through loop once too often

  30. Example: Making Cookies Design and implement a Java program with ten factories, each specializing in its particular kind of cookie, which generate their cookies in a row at the top of the panel. When “Create Cookies” button is pressed, all factories should make a cookie just below the factory’s position and drop it so it falls down and then out of the panel.

  31. Quick Look at Design (1/2) Some things we’ve seen before: • Factory- constructs other classes without knowing actual type of object to be constructed • Java program- uses a javax.swing.JFrame • panel - JPanel, cookies are images graphically contained in a panel • cookie - java.awt.Image that has behavior to move down panel • row - javax.swing.JPanel to contain cookie factories • Position - set using methods of our specialized java.awt.Image class

  32. Quick Look at Design (2/2) Things that aren’t as apparent: • how do we make button do something for all factories in sequence? • how do we deal with ten cookie factories usefully?

  33. Create ‘DropButton’ Button (1/2) DropButton extends javax.swing.JButton and adds a java.awt.event.ActionListener that does something useful – standard pattern

  34. package Demos.CookieArray; public class DropButton extends JButton{ //CookieFactory is defined elsewhere //(actual definition is not important here) public DropButton(CookieFactory[] cfArray){ super("Create Cookies"); this.addActionListener(new DropListener(cfArray)); } } Create ‘DropButton’ Button (2/2) package Demos.CookieArray; public class DropListener implements ActionListener{ private CookieFactory[] _cfArray; public DropListener(CookieFactory[] cfArray){ _cfArray = cfArray; } public void actionPerformed(ActionEvent e){ /* when button is pressed, use loop to tell every every factory in array to make Cookie */ for (int i=0; i< _cfArray.length; i++){ _cfArray[i].makeCookie(); } } }

  35. Out-of-Bounds Problems (1/2) • Careful about bounds of loops that access arrays! • Java will throw ArrayIndexOutOfBoundsException if index is negative since sequence starts at 0 • Also will throw ArrayIndexOutOfBoundsException if index is ≤array size; remember that array goes from 0 to n-1 • exceptions can lead to crashes so be careful • Java has a catch keyword which can be used to “catch” and handle exceptions… used in CS16 • Brief intro to how to try experimental code and catch errors at tail end of CS15

  36. Out-of-Bounds Problems (2/2) • Prevent out-of-bounds problems by explicitly checking with conditionals before accessing public boolean isIndexInBounds (int index) { return ((index >=0) && (index < _cookieFactoryArray.length)); } • don’t need to do this in for loop, but could be useful in indefinite loop • Remember the power of hand simulation! • In general, important to check for legal values of parameters yourself to prevent problems (don’t always have to make a different method to do this check, though)

  37. Multi-Dimensional Arrays (1/2) • Say we wanted to model a chess board • not a linear group of squares • more like a grid of squares • Can declare an array to be 2 (or more) dimensions, by adding more brackets • one pair per dimension • 2D: int [][] grid = new int [a][b]; • 3D: int [][][] cube = new int [x][y][z]; // a, b, x, y, z are ints whose values are set elsewhere

  38. Multi-Dimensional Arrays (2/2) • Multi-dimensional array is an array of arrays of… • The syntax above is for rectangular, cuboid, etc. multi-dimensional arrays • since multi-dimensional arrays are just arrays of arrays of arrays, possible (using different syntax) to have jagged arrays, where each sub-array is of a different length • thus can have a “triangle” shaped array • don’t use this is CS15; even in CS16 and beyond, it is unlikely you will use this

  39. Two-Dimensional Array Examples • Pixel Array • 2D Array size: pxl width by pxl height • Array indices: x, y • Element type: RGB color • Connect Four • 2D Array size: 6 by 7 • Array indices: row, column • Element type: checker • The Sunlab as a 2D array! • 2D Array size: 10 by 8 (est) • Array indices: row, column • Element type: computer

  40. Representing Multi-Dimensional arrays (1/2) • Let’s say we want to represent this grid of numbers:

  41. Representing Multi-Dimensional arrays (2/2) • How do we want to represent this grid? There are two equally valid options:

  42. Ways to Think About Array Storage Multi-dimensional arrays in Java do not make a distinction between rows or columns - think about a one-dimensional array - doesn’t really matter if we call it a “row” or a “column” (unlike in many other languages!) you may think of it as an ordered sequence stored in contiguous positions in memory - no intrinsic geometry/layout implied

  43. Visualization is less important than indexing - make sure you are consistent in the way you index into your 2D array throughout your program! Ways to Think About Array Storage • So the following two visualizations of a two-dimensional array (called array) are equally valid column-major order, i.e., first index is column index (e.g., purple ball is at array[0][2] - 0th column, 2nd row) row-major order, i.e., first index is row index (e.g., purple ball is at array[0][2] - 0th row, 2nd column)

  44. Thinking About Arrays for Graphics (1/2) • Consider 2D array of booleans where you want to turn on a pixel for each true value at the corresponding (row, column) position • instead of Boolean, could store pixel’s color value • In computer graphics, think column-major order, i.e., 1st index as x coordinate and 2nd as y coordinate • each x-coordinate holds an array of y-coordinates

  45. Thinking About Arrays for Graphics (2/2) x (1, 0) grid[3][2]

  46. Example: Size of 2D Arrays public class ArraySize{ //using rows and columns as indices is arbitrary private static final int NUM_ROWS = 10; private static final int NUM_COLS = 5; • public ArraySize(){ • //String is just an arbitrary choice! • String[][] myArray = new String[NUM_ROWS][NUM_COLS]; • System.out.println("Number of rows = " + NUM_ROWS); • System.out.println("Number of columns = " + NUM_COLS); • System.out.println("Size of array = " + this.find2DArraySize(myArray)); • } • public int find2DArraySize(String[][] array){ • int numRows = array.length; • int numCols = array[0].length; //element 0 is an array • return (numRows * numCols); • } • } array.length gives the size of the first dimension (you decide whether that is the row or the column) array[0].length gives the size of the second dimension

  47. Common Array Errors - Watch Out! (1/2) • Assigning a scalar to an array int[] myArray = 5; • 5 is not an array • to initialize array elements you must loop over the array and assign values at each index • int[] myArray = new int[20]; • for (int i=0; i<myArray.length; i++){ • myArray[i] = 5; • }

  48. Common Array Errors - Watch Out! (2/2) • Assigning an array to a scalar Array = new int[1000]; int myInt = myArray; • Assigning arrays of different dimension to each other int[] myIntArray = new int[23]; int[][] my2DIntArray = new int[2][34]; myIntArray = my2DIntArray; • Never assign arrays of different dimensions or you will become familiar with the error: • “Incompatible type for =. Can’t convert int[] to int[][]” • Similar message for assigning arrays of the wrong type

  49. Let’s Make a Board … What Kind? • Warm-up for Tetris… • Let’s start with a specification: Write a Java program that draws sixty-four squares in a grid-like pattern of alternating colors, much like a checker board. The checker board should be eight squares long and eight squares wide. Additionally, the user should be able to click on buttons and change the colors in an individual row or column of the board from the traditional red and black to the new & bold colors white and blue. There should be sliders that allow the user to select which row or column should switch its colors when a button is pressed.

  50. Quick Look at Design • Some things we’ve seen before: • java program - uses a javax.swing.JFrame • buttons - uses javax.swing.JButtons • slider- (JSlider) component for choosing one of many numeric values • red, black, white, blue- java.awt.Colors • Things that aren’t as apparent • sixty-four squares - we know about one square, Shape.RectangleShape, but 64? • checker board- let’s make a 2D 8x8 array of squares • row, column- indices into array • This sample program has crucial design hints for Tetris. Pay close attention!

More Related