Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays. 2 Why do we care (about arrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep.

Similar presentations


Presentation on theme: "Arrays. 2 Why do we care (about arrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep."— Presentation transcript:

1 Arrays

2 2 Why do we care (about arrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep track of where each one is? int car1X, car1Y, car2X, car2Y, car3X, car3Y…… How about keeping them in a ‘table’ or a ‘grid’ CarX table: Each ‘column’ has a number You can refer to CarX table, column 3 for Car3… Note that all of the values in the row must be the same data type 12345678910

3 3 When to use an Array Any time a program requires multiple instances of similar data, it might be time to use an array. For example, an array can be used to store: The scores of four players in a game A selection of 10 colors in a design program A list of fish objects in an aquarium simulation The days per month in a scheduling program

4 4 What is an array? A variable is a named location in memory. An array is a named set of locations in memory A ‘list’ of variables Each element of the list has a number called an ‘index’ Starts at 0!

5 How to Declare an array (Step 1) Create the array variable (with the name and type) Make a named ‘list’ with the following parts: Type Square Braces Array name semicolon int[ ] arrayOfInts ; You are ‘declaring’ that There is an array named arrayOfInts The elements inside are of type int You have not (YET) declared how many are in inside Other Rules: Arrays can be declared anywhere you can declare a variable Do not use ‘reserved’ words or already used names 5

6 How to Create an array (Step 2) Reserve memory for all of the elements in the list: Array name Keyword Type Size semicolon arrayOfInts = new int [42] ; You are reserving memory for: The array named arrayOfInts Needs storage for [42] elements the size of type int Now you (and the compiler) know how many are in inside You cannot change the size after you declare it! 6 arrayOfInts [0] [1] [2] [3] [4] … [41] int

7 Two Steps on one line: Declare and Create at the same time: Type Braces Array name Keyword Type Size semi int [] arrayOfInts = new int [42] ; You are ‘declaring’ that There is an array named arrayOfInts The elements inside are of type int You are reserving memory for the array Needs storage for [42] elements the size of type int Note that the size cannot be changed, so you should make enough room when you start! 7

8 Initializing an Array The ‘long’ way The one-liner way: The compiler counts the number of elements (3) Sets the size automatically! Fills the contents with the values inside the { }; Values are separated by commas 8 int [] stuff = new int[3]; stuff[0] = 8; stuff[1] = 3; stuff[2] = 1; int [] stuff = { 8, 3, 1 };

9 Initializing with Iteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Using a while loop: 9 int[] die = new int[5]; die[0] = (int)random(0,6); die[1] = (int)random(0,6); die[2] = (int)random(0,6); die[3] = (int)random(0,6); die[4] = (int)random(0,6); int n = 0; while (n < 5) { die[n] = (int)random(0,6); n = n + 1; } int n = 0; while (n < 5) { die[n] = (int)random(0,6); n = n + 1; }

10 Initializing with Iteration Rolling 5 dice (Yahtzee) Example The ‘hard’ way Using a for loop: 10 int[] die = new int[5]; die[0] = (int)random(0,6); die[1] = (int)random(0,6); die[2] = (int)random(0,6); die[3] = (int)random(0,6); die[4] = (int)random(0,6); for (int n = 0; n < 5; n++ ) { die[n] = (int)random(0,6); } for (int n = 0; n < 5; n++ ) { die[n] = (int)random(0,6); }

11 Length of the Array 11 Using a for loop to initialize an array: Note the use of values.length The array knows how long it is! float[] values = new float[6]; for (int i = 0; i < values.length; i++) values[i] = 0;

12 Walking off the end of the array… A very common problem is trying to access an element in the array that doesn’t exist: Remember that we start at element 0 What is the index of the last element? ______ What happens if we try to access element [10]? 12 for (int i = 0; i <= 10; i++ ) { xpos[i] = 0; } Exception in thread "Animation Thread" java.lang.ArrayIndexOutOfBoundsException: 10 at OutOfBounds.setup(OutOfBounds.java:21) int[] xpos = new int[10];

13 Example: The Snake Declare and initialize two ‘global’ arrays: Initialize them in setup() Each time the mouse is clicked, store the mouseX and mouseY into the next available spot in the array (fill from left to right) 13 int[] xpos = new int[10]; int[] ypos = new int[10]; for (int i = 0; i < xpos.length; i++ ) { xpos[i] = 0; ypos[i] = 0; }

14 Arrays of Objects Using arrays to store multiple objects is a very powerful programming feature We will use the Car class and create an array of unique cars 14

15 The ‘Car’ Class Revisited class Car { color c; float xpos, ypos, xspeed; Car(color cp, float xposp, float yposp, float xspeedp) { c = cp; xpos = xposp; ypos = yposp; xspeed = xspeedp; } void display() { rectMode(CENTER); stroke(0); fill(c); rect(xpos,ypos,20,10); } void move() { xpos = xpos + xspeed; if (xpos > width) { xpos = 0; }

16 Step 1: Type Square Braces Array name semicolon Car[ ] cars ; Step 2: Array name Keyword Type Size semicolon cars = new Car [5] ; Or the ‘one-liner’ version Type [ ] Array name Keyword Type[Size] semi Car[ ] cars = new Car[5] ; 16 cars [0] [1] [2] [3] [4] [5] empty

17 Use a loop to fill up the array! void setup() { size(200,200); smooth(); for (_____________________________) { ___________________________________ } 17 Car color xpos ypos xspeed Car cars [0] [1] [2] [3] [4] [5] color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed color xpos ypos xspeed

18 And let’s get them on the road! Use a loop to move and display them! void draw() { background(255); for (_____________________________) { ___________________ //call the move() function ___________________ //call the disp() function } 18

19 Interactive Objects (Stripe Example) 19 class Stripe{ float x; float w; boolean mouse; Stripe(float xp, float wp){ __________ } void display(){.... } void rollover(){.... }

20 Additional Processing Array features Processing provides a set of functions to help manage arrays: shorten() concat() -- Puts two arrays together subset() append() splice() expand() – Make an array larger in size! sort() – Sort all the elements in the array reverse() – Reverse the order of all elements 20

21 append() String[] s = { "OH", "NY", "CA"}; s = append(s, "MA"); for (int i = 0; i < s.length; i++){ System.out.println(s[i]); } 21

22 Example: append() function Start with an array of one object. Each time the mouse is pressed, a new object is created and appended to the end of the original array. 22

23 23 class Ball { float x; float y; float speed; float w; Ball(float tempX, float tempY, float tempW) { x = tempX; y = tempY; w = tempW; speed = 0; } void gravity() { // Add gravity to speed speed = speed + gravity; } void move() { y = y + speed; if (y > height) { speed = speed * -0.95; y = height; } void display() { // Display the circle fill(175); stroke(0); ellipse(x,y,w,w); }

24 24 // Start with an array with just one ball.... void setup({ // Initialize the first ball... } void draw(){ // Display all the balls in the current array... } void mousePressed(){ // Create a new ball object at the mouse location and append it to the array.... }

25 Two-Dimensional Arrays 25 //One dimensional array int[] myArray = new int[10]; for (int i = 0; i < myArray.length; i++){ myArray[i] = 0; } //Two dimensional array int row = 10; int col = 15; int[] myArray = new int[row][col]; for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++) { myArray[i] = 0; } //Using array initializer int[][] myArray = { {1, 2, 3, 4 }, {5, 6, 7, 8}, {9, 10, 11, 12} };

26 Example: Grayscale Image 26 size(200,200); int row = width; int col = height; float[][] myArray = new float[row][col]; // Initialize 2D array values for (int i = 0; i < row; i ++ ) { for (int j = 0; j < col; j ++ ) { myArray[i][j] = random(255); } // Draw points for (int i = 0; i < row; i ++ ){ for (int j = 0; j < col; j ++ ) { stroke(myArray[i][j]); point(i,j); }


Download ppt "Arrays. 2 Why do we care (about arrays)? What if you have a whole bunch of cars (or aliens or balls or ???) bouncing around the screen? How do we keep."

Similar presentations


Ads by Google