1 of 163

New Slide Presentation: 2d arrays

1

2 of 163

Grades are due Thursday 2/24

To be counted for this 6 week marking period I need the following assignments by Wednesday 2/23:

  • Create your own Fractal, Sierpinski Triangle, Palindrome Checker, Pig Latin and Google Billboard
  • Codingbat recursion1, recursion2, recursion3, palindrome, piglatin and googlebillboard
  • Recursion Worksheets #1 and 2
  • NOTE: minesweeper and the minesweeper codingbat will not be graded as part of this marking period
  • If you need help completing an assignment let me know! I’m free before school, blocks 0,4, and 6

2

3 of 163

2 dimensional arrays

  • Can be thought of as a “grid” with rows and columns
  • Used for:
    • Digital Images
    • Board games (e.g. chess, checkers, bingo)
    • Maps
    • Tables (e.g. Periodic Table)
    • Spreadsheets
    • Seats in a theater
    • Days on a calendar

3

4 of 163

2 dimensional arrays

  • Here’s a 2d array with 2 rows and 3 columns

4

5 of 163

2 dimensional arrays

int [][] naNums= {{-3, -1, 5},

{7, 12, 13} };

/*Java automatically sizes the array to 2 rows and 3 columns

Note: rows first, then columns!*/

System.out.println(naNums[1][2]);

//displays 13

System.out.println(naNums[2][1]);

//Out of bounds exception!

5

6 of 163

2 dimensional arrays

  • How many arrays are in the following declaration and initialization?

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

6

7 of 163

2 dimensional arrays

  • There are 5 arrays total!
  • Each array has its own pair of curly braces: white, yellow, orange, green and red

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

7

8 of 163

2 dimensional arrays

  • We can think of a 2d array as an “Array of Arrays”

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

System.out.println(alphabet[0][1]);

System.out.println(alphabet[1][0]);

System.out.println(alphabet[3][4]);

System.out.println(alphabet[4][3]);

8

9 of 163

2 dimensional arrays

  • We can think of a 2d array as an “Array of Arrays”

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

System.out.println(alphabet[0][1]);

System.out.println(alphabet[1][0]);

System.out.println(alphabet[3][4]);

System.out.println(alphabet[4][3]);

9

10 of 163

Find the output

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

System.out.print(alphabet[3][3]);

System.out.print(alphabet[0][0]);

System.out.print(alphabet[1][3]);

System.out.println(alphabet[2][4]);

System.out.println(alphabet.length);//white

System.out.println(alphabet[0].length);//yellow

System.out.println(alphabet[3].length);//red

10

11 of 163

11

Review: Loops

  • Loops make things happen over and over again
  • If you are doing the same thing over and over again with small variations, use a loop
  • For example, you could write a loop to display six Xs:

X X X X X X

12 of 163

12

Review: Loops

for(int i = ?; i <= ?; i?)

{

System.out.print("X ");

}

X X X X X X

13 of 163

13

Review: Loops

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

X X X X X X

14 of 163

14

Review: Nested Loops

  • Now, how would I repeat that pattern three times so that it looked like this?

X X X X X X

X X X X X X

X X X X X X

15 of 163

15

Review: Nested Loops

for(??)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

??

}

X X X X X X

X X X X X X

X X X X X X

16 of 163

16

Review: Nested Loops

for(int j = 1; j <= 3; j++)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

System.out.println(); //ends the line

}

X X X X X X

X X X X X X

X X X X X X

17 of 163

17

Review: Nested Loops

  • Putting a loop inside another loop is an example of Nesting

for(int j = 1; j <= 3; j++)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

System.out.println(); //ends the line

}

18 of 163

18

Review: Nested Loops

  • Notice the row and column arrangement

for(int j = 1; j <= 3; j++)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

System.out.println(); //ends the line

}

X X X X X X

X X X X X X

X X X X X X

19 of 163

19

Review: Nested Loops

  • Notice the row and column arrangement

for(int j = 1; j <= 3; j++)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

System.out.println(); //ends the line

}

X X X X X X

X X X X X X

X X X X X X

20 of 163

20

Review: Nested Loops

  • Which loop is generating the three rows?
  • Which loop is generating the six columns?

for(int j = 1; j <= 3; j++)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

System.out.println(); //ends the line

}

X X X X X X

X X X X X X

X X X X X X

21 of 163

21

A good thing to remember

  • The outer loop can be used to generate a number of rows
  • The inner loop can be used to generate a number of columns

for(int j = 1; j <= 3; j++)

{

for(int i = 1; i <= 6; i++)

{

System.out.print("X ");

}

System.out.println(); //ends the line

}

22 of 163

Codingbat 2d array problems

  • The minesweeper problem set has 10 2d array problems

22

23 of 163

Codingbat: countFives

  • Click the Show Hint button and copy and paste the 2d array into the function

23

24 of 163

Codingbat: countFives

  • Declare and initialize a local variable to hold the number of 5s
  • Write nested loops in row column order to count the number of 5s

24

25 of 163

Nested loops

  • Let's say we wanted to make a 10x10 times table:

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

25

26 of 163

Nested loops

  • Let's start with the first row

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

  • It would be easy enough to write a loop that makes the numbers 1 through 10

26

27 of 163

Nested loops

  • Let's start with the first row

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20 x2

3 6 9 12 15 18 21 24 27 30 x3

4 8 12 16 20 24 28 32 36 40 x4

5 10 15 20 25 30 35 40 45 50 x5

6 12 18 24 30 36 42 48 54 60 x6

7 14 21 28 35 42 49 56 63 70 x7

8 16 24 32 40 48 56 64 72 80 x8

9 18 27 36 45 54 63 72 81 90 x9

1020 30 40 50 60 70 80 90 100 x10

  • We'd put that loop inside another loop, that "multiplies" it

27

28 of 163

Nested loops

for(int nJ = 1; nJ <= 10; nJ++)

System.out.print(nJ + "\t");

//inside loop counts columns 1 to 10

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20 x2

3 6 9 12 15 18 21 24 27 30 x3

4 8 12 16 20 24 28 32 36 40 x4

5 10 15 20 25 30 35 40 45 50 x5

6 12 18 24 30 36 42 48 54 60 x6

7 14 21 28 35 42 49 56 63 70 x7

8 16 24 32 40 48 56 64 72 80 x8

9 18 27 36 45 54 63 72 81 90 x9

1020 30 40 50 60 70 80 90 100 x10

28

29 of 163

Nested loops

for(int nI = 1; nI <= 10; nI++)

{

for(int nJ = 1; nJ <= 10; nJ++)

System.out.print( ?? + "\t");

??

}//outside loop counts rows 1 to 10

//(inside loop column)*outside row

//ends the line

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20 x2

3 6 9 12 15 18 21 24 27 30 x3

4 8 12 16 20 24 28 32 36 40 x4

5 10 15 20 25 30 35 40 45 50 x5

6 12 18 24 30 36 42 48 54 60 x6

7 14 21 28 35 42 49 56 63 70 x7

8 16 24 32 40 48 56 64 72 80 x8

9 18 27 36 45 54 63 72 81 90 x9

10 20 30 40 50 60 70 80 90 100 x10

29

30 of 163

Nested loops

30

31 of 163

Nested loops and 2D arrays

  • Because 2D arrays and nested loops both work with rows and columns, they are often used together
  • For instance, let’s say that we wanted to display all the elements of the 2D array alphabet in row column order

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

31

32 of 163

Nested loops and 2D arrays

  • This loop will loop through the 4 rows

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

for(int r = 0; r < alphabet.length; r++)

32

33 of 163

Nested loops and 2D arrays

  • Then we want a second loop to loop through each of the 4 arrays

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

for(int r = 0; r < alphabet.length; r++)

for(int c = 0; c < alphabet[r].length; c++)

System.out.print(alphabet[r][c]);

33

34 of 163

This is necessary if the rows don’t all have the same number of elements

  • Then we want a second loop to loop through each of the 4 arrays

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

for(int r = 0; r < alphabet.length; r++)

for(int c = 0; c < alphabet[r].length; c++)

System.out.print(alphabet[r][c]);

34

35 of 163

You may be familiar with this 2d array where the rows don’t all have the same number of elements

35

36 of 163

Here’s another non-rectangular 2d array where different rows have a different number of columns

36

37 of 163

Here’s another non-rectangular 2d array where different rows have a different number of columns

37

38 of 163

Practice Quiz Question:�Complete the 2 nested loops

  • Copy the following code into Processing, or fork this repl.it

String [][] words ={

{"the", "quick", "brown", "fox"},

{"jumps", "over"},

{"the", "lazy", "dog"}

};

for(int r = ??; ??; ??)

for(int c = ??; ??; ??)

System.out.print(words[r][c] + " ");

Output

38

39 of 163

Buttons and GUIs

  • A GUI (Graphical User Interface) uses things like checkboxes, sliders, text fields and buttons for user input
  • While GUIs aren’t built in to Java or Processing, they can be added as a library
  • We’re going to add the Guido library to processing
  • (GUIdo, get it?)

39

40 of 163

Adding Guido

  • Start Processing
  • One way is to double click on processing.exe

40

41 of 163

Adding Guido

  • Choose Sketch | Import Library | Add Library

41

42 of 163

Adding Guido

  • Type guido in the search box
  • Click on Guido by Florian Jenett to install

42

43 of 163

Example code

  • Choose File | Examples
  • Expand Contributed Libraries | Guido and choose button

43

44 of 163

Example code

  • Run the program
  • You should see a grid of buttons

44

45 of 163

Adding Guido Manually

  • If for some reason Guido still doesn’t work, ask me for a copy of the Guido folder
  • Then copy the Guido folder in to Documents | Processing | Libraries

45

46 of 163

Defining a MyButton class and using it

import de.bezier.guido.*;

private MyButton button1;

public void setup (){

size(400, 400);

textAlign(CENTER);

textSize(24);

// make the manager

Interactive.make( this );

// create a button

button1 = new MyButton( 190, 190, 20, 20 );

}

public void draw (){

background( 0 );

if(button1.isOn())

text("Button is Activated", 200, 240);

}

public class MyButton{

private float x, y, width, height;

private boolean on;

public MyButton ( float xx, float yy, float w, float h ){

x = xx; y = yy; width = w; height = h;

Interactive.add( this ); // register it with the manager

}

public void mousePressed () { on = !on;}

public void draw () {

if ( on ) fill( 200 );

else fill( 100 );

rect(x, y, width, height);

}

public boolean isOn(){return on;}

}

46

47 of 163

Defining a MyButton class

public class MyButton

{

private float x, y, width, height;

private boolean on;

public MyButton ( float xx, float yy,

float w, float h )

{

x = xx; y = yy; width = w; height = h;

Interactive.add( this );

// register it with the manager

}

public void mousePressed () { on = !on;}

public void draw ()

{

if ( on ) fill( 200 );

else fill( 100 );

rect(x, y, width, height);

}

public boolean isOn(){return on;}

}

47

48 of 163

Using MyButton

import de.bezier.guido.*;

private MyButton button1;

public void setup ()

{

size(400, 400);

textAlign(CENTER);

textSize(24);

// make the manager

Interactive.make( this );

// create a button

button1 =

new MyButton( 190, 190, 20, 20 );

}

public void draw ()

{

background( 0 );

if(button1.isOn())

text("Button is Activated",200, 240);

}

48

49 of 163

In class: Copy and paste the code below and then modify it to have two larger buttons. Display the text only if both are on.

import de.bezier.guido.*;

private MyButton button1;

public void setup (){

size(400, 400);

textAlign(CENTER);

textSize(24);

// make the manager

Interactive.make( this );

// create a button

button1 = new MyButton( 190, 190, 20, 20 );

}

public void draw (){

background( 0 );

if(button1.isOn())

text("Button is Activated", 200, 240);

}

public class MyButton

{

private float x, y, width, height;

private boolean on;

public MyButton ( float xx, float yy, float w, float h )

{

x = xx; y = yy; width = w; height = h;

Interactive.add( this ); // register it with the manager

}

public void mousePressed () { on = !on;}

public void draw ()

{

if ( on ) fill( 200 );

else fill( 100 );

rect(x, y, width, height);

}

public boolean isOn(){return on;}

}

49

50 of 163

50

The Game of Life

  1. Any live cell with two or three live neighbours survives
  2. Any dead cell with three live neighbours becomes a live cell
  3. All other live cells die in the next generation. Similarly, all other dead cells stay dead

The Game of Life probably isn't what you think, it's a program that simulates how cells might grow or die based on a small set of rules

51 of 163

51

Video: The Game of Life

52 of 163

52

The Game of Life

  • Play the Game of Life online at playgameoflife.com

53 of 163

53

Stable and Repeating Patterns

  • There are many characteristic patterns that will help you identify if your Game of Life is working correctly

54 of 163

54

Getting Started with Game of Life

  • If you are not sure of how to start, there is a suggested list of steps to complete the program

55 of 163

55

create two integer constants NUM_ROWS and NUM_COLS

  • Constants are public, final and static
  • If you think of variables as “boxes”, constants are locked “boxes”
  • The value of a constant cannot be changed
  • Constants are declared outside of functions

public final static int SOME_CONSTANT = 5;

public void setup() {

//constants are NOT local to a function

}

create two integer constants NUM_ROWS and NUM_COLS

56 of 163

Declaring and Initializing 2d arrays: How many rows and columns?

int [][] naNums;

naNums = new int[2][3];

56

57 of 163

Declaring and Initializing 2d arrays: 2 rows and 3 columns

int [][] naNums;

naNums = new int[2][3];

57

58 of 163

Declaring and Initializing 2d arrays: What would the output be?

int [][] naNums;

naNums = new int[2][3];

System.out.println(naNums[1][1]);

58

59 of 163

Zero!�In Java, uninitialized values are 0 or equivalent

int [][] naNums;

naNums = new int[2][3];

System.out.println(naNums[1][1]);

59

60 of 163

Now, what would the output be?

boolean [][] naNums;

naNums = new boolean[2][3];

System.out.println(naNums[1][1]);

60

61 of 163

false�(the boolean equivalent of zero)

int [][] naNums;

naNums = new int[2][3];

System.out.println(naNums[1][1]);

61

62 of 163

What would the output be with a String?

String [][] naNums;

naNums = new String[2][3];

System.out.println(naNums[1][1]);

62

63 of 163

null(the Object or pointer equivalent of zero)

String [][] naNums;

naNums = new String[2][3];

System.out.println(naNums[1][1]);

  • Note NO ERROR
  • A NullPointerException is when you try to use a null pointer
  • naNums[1][1].length() would cause an error

63

64 of 163

Initializing 2 dimensional arrays

int [][] naNums;

naNums = new int[2][3];

  • Typically, nested loops are used to initialize each value in a 2d array. The outside loop controls the row, and the inside the column

for(int row = 0; row < 2; row++)

for(int col = 0; col < 3; col++)

naNums[row][col] = 3;

64

65 of 163

Initializing a 2d array of Life

private Life[][] buttons;

public void setup ()

{

//other java not shown

buttons = ??

65

66 of 163

Initializing a 2d array of Life

private Life[][] buttons;

public void setup ()

{

//other java not shown

buttons = new Life ??;

66

67 of 163

Initializing a 2d array of Life

private Life[][] buttons;

public void setup ()

{

//other java not shown

buttons = new Life[20][20];

67

68 of 163

Even better: use the constants!

private Life[][] buttons;

public final static int NUM_ROWS = 20;

public final static int NUM_COLS = 20;

public void setup ()

{

//other java not shown

buttons = new Life[NUM_ROWS][NUM_COLS];

68

69 of 163

What’s the mistake?

private Life[][] buttons;

public void setup ()

{

//other java not shown

Life[][] buttons = new Life[20][20];

69

70 of 163

buttons is declared twice

private Life[][] buttons;

public void setup ()

{

//other java not shown

Life[][] buttons = new Life[20][20];

70

71 of 163

How many new Lifes have been created? (Hint: it's a trick question)

private Life[][] buttons;

public void setup ()

{

//other java not shown

buttons = new Life[20][20];

71

Another way to ask the question would be: “What value is in each cell of buttons after this code executes?”

Hint: look back at slides 61 & 62

72 of 163

None yet! Imagine an array with 20 rows and columns each of which is empty

private Life[][] buttons;

public void setup ()

{

//other java not shown

buttons = new Life[20][20];

72

73 of 163

Use nested loops in row column order to initialize buttons

private Life[][] buttons;

public void setup ()

{

//other Java code not shown

for(int r = ??; r < ??; r++)

for(int c = ??; c < ??; c++)

buttons[r][c] = new Life(??,??);

//other Java code not shown

73

Notice the Life constructor takes 2 arguments, the row and the column

74 of 163

Getting the grid to appear

  • Just a couple more steps and you should have a grid of buttons
  • Uncomment the first two lines in the Life constructor public Life (int row, int col)
  • In draw under the comment //use nested loops to draw the buttons here write nested loops (again using the constants) to draw each button to the screen.

74

75 of 163

Getting the grid to appear

  • Run the program, you should now see a random grid of buttons similar to the picture below. If you click on the button it should turn off and on.

75

76 of 163

76

Video: Conway’s Game of Life Part 2

77 of 163

77

Counting Neighbors

  • The life and death of cell depends on the 8 neighbors that surround it

create two integer constants NUM_ROWS and NUM_COLS

78 of 163

78

Counting Neighbors

  • If a living cell has fewer than two or more than three living neighbors it dies

create two integer constants NUM_ROWS and NUM_COLS

79 of 163

79

Counting Neighbors

  • If an empty cell has exactly three living neighbors it comes to life

create two integer constants NUM_ROWS and NUM_COLS

80 of 163

80

The 8 possible neighbors

  • Here are the 8 possible neighbors of a cell at (row,col)

create two integer constants NUM_ROWS and NUM_COLS

(row, col)

(row, col-1)

(row, col+1)

(row+1, col)

(row+1, col-1)

(row+1, col+1)

(row-1, col)

(row-1, col-1)

(row-1, col+1)

81 of 163

81

Counting Neighbors

  • Cells on the corners and edges of the grid will have less than 8 valid neighbors

create two integer constants NUM_ROWS and NUM_COLS

82 of 163

What are valid cells?

  • Valid means the cell exists, it’s on the grid
  • Positions that would be outside the edges of the grid are not valid

create two integer constants NUM_ROWS and NUM_COLS

valid

valid

valid

valid

valid

valid

valid

valid

valid

valid

valid

valid

valid

valid

valid

not valid

not valid

not valid

not valid

not valid

not valid

not valid

not valid

not valid

83 of 163

83

Codingbat

  • You may find it helpful to do these four codingbat problems before you code isValid and countNeighbors in the Game of Life

create two integer constants NUM_ROWS and NUM_COLS

84 of 163

84

Game of Life due date 3/12

  • codingbat minesweeper problem set due tomorrow Friday March 5
  • Game of Life due one week from tomorrow Friday March 12

create two integer constants NUM_ROWS and NUM_COLS

85 of 163

85

Spraypaint Game of Life

  • Here’s an interesting version of the Game of Life

www.fractalteapot.com/portfolio/game-of-life/

create two integer constants NUM_ROWS and NUM_COLS

86 of 163

86

Why do we need the “buffer”?

  • In computer graphics a buffer typically stores the value for each pixel shown on the display
  • We’ll use the buffer to store a snapshot of the grid
  • If we don’t use a buffer, the result doesn’t work correctly as you can see in this animation that doesn’t use a buffer

create two integer constants NUM_ROWS and NUM_COLS

87 of 163

87

Why do we need the “buffer”?

  • The buffer allows us to store the current state of the grid and “freeze” it in time
  • It allows us to apply the rules to all cells simultaneously
  • You can see that this correct animation that uses a buffer gives a completely different result

create two integer constants NUM_ROWS and NUM_COLS

88 of 163

88

Why do we need the “buffer”?

  • First, we need to go through the entire array and count the neighbors of every cell . . .

create two integer constants NUM_ROWS and NUM_COLS

0

0

1

2

2

0

1

2

3

2

0

1

2

1

1

89 of 163

89

Why do we need the “buffer”?

  • . . . and then apply the rules to all the cells at the same time

create two integer constants NUM_ROWS and NUM_COLS

0

1

2

2

1

0

1

1

1

1

0

1

2

2

1

90 of 163

90

Why do we need the “buffer”?

  • In this example none of the cells survive

create two integer constants NUM_ROWS and NUM_COLS

0

0

0

0

0

0

0

0

0

0

0

0

0

0

0

91 of 163

Quizziz

create two integer constants NUM_ROWS and NUM_COLS

92 of 163

92

Getting Started with Minesweeper

  • If you are not sure of how to start, there is a suggested list of steps to complete the program

93 of 163

93

create two integer constants NUM_ROWS and NUM_COLS

  • Your program should run without errors after you complete each step

create two integer constants NUM_ROWS and NUM_COLS

94 of 163

94

initialize the 2d array buttons

  • Remember to use your constants for the number of rows and columns!

create two integer constants NUM_ROWS and NUM_COLS

95 of 163

95

Use nested loops to create a new MSButton for each row column pair

  • Remember to use your constants for the number of rows and columns!

create two integer constants NUM_ROWS and NUM_COLS

96 of 163

96

Uncomment the first two lines of the MSButton constructor

  • You should now see a grid of buttons
  • If you click on the button it should turn white

create two integer constants NUM_ROWS and NUM_COLS

97 of 163

97

go to line 7, and initialize bombs to be a new empty ArrayList of type MSButton

create two integer constants NUM_ROWS and NUM_COLS

98 of 163

98

Add code to the setBombs() function

  • It should generate a random row and column number
  • Remember to use your constants for the number of rows and columns!

create two integer constants NUM_ROWS and NUM_COLS

99 of 163

99

Uncomment the 3rd and 4th lines of MSButton draw()

  • Add the button at the random location to bombs
  • To test your program, print that location, click the button and check if the button turns red

create two integer constants NUM_ROWS and NUM_COLS

100 of 163

100

Add a while loop in setBombs()

  • Use the contains() function to check to see if the button at the random location is already in bombs. If it isn't then add it
  • Test your program repeatedly to make sure you are getting the correct number of bombs

create two integer constants NUM_ROWS and NUM_COLS

101 of 163

Recursion in Minesweeper

  • If you press a button that has no mine count the 8 adjacent buttons are also pressed
  • If any of those neighbors have no mine count, their 8 neighbors are also pressed
  • And so on. . .

101

102 of 163

Remove marked blobs to the left

  • Problem: Write code so that when a blob is clicked any adjacent marked blobs to the left are also unmarked

102

  • What would happen if I clicked on the indicated blob?

103 of 163

Remove marked blobs to the left

  • Problem: Write code so that when a blob is clicked any adjacent marked blobs to the left are also unmarked

103

104 of 163

Remove marked blobs to the left

  • Problem: Write code so that when a blob is clicked any adjacent marked blobs to the left are also unmarked

104

  • Now what would happen if I clicked on the indicated blob?

105 of 163

Remove marked blobs to the left

  • Problem: Write code so that when a blob is clicked any adjacent marked blobs to the left are also unmarked

105

106 of 163

Remove marked blobs to the left

  • Problem: Write code so that when a blob is clicked any adjacent marked blobs to the left are also unmarked

106

  • Now what would happen if I clicked on the indicated blob?

107 of 163

Remove marked blobs to the left

  • Problem: Write code so that when a blob is clicked any adjacent marked blobs to the left are also unmarked

107

108 of 163

Remove marked blobs to the left

  • The blobs are in a two dimensional array called blobs
  • The Blob class has private member variables for the row and column

108

109 of 163

Remove marked blobs to the left

  • The Blob class has public member functions isValid() and isMarked()

109

110 of 163

Practice Quiz Question

import de.bezier.guido.*;

private Blob[][] blobs;

void setup ()

{

size(400, 400);

// make the manager

Interactive.make( this );

blobs = new Blob[10][10];

for (int r = 0; r < 10; r++)

for (int c = 0; c < 10; c++)

blobs[r][c] = new Blob(r, c);

}

void draw() {

}//empty

public class Blob

{

private int r, c;

private float x, y, width, height;

private boolean marked;

public Blob ( int rr, int cc )

{

width = 40;

height = 40;

r = rr;

c = cc;

x = c*width;

y = r*height;

marked = Math.random() < .5;

Interactive.add( this ); // register it with the manager

}

public boolean isMarked()

{

return marked;

}

public boolean isValid(int row, int col)

{

if (row>=0 && row<10 && col>=0 && col<10)

return true;

else

return false;

}

public void mousePressed ()

{

marked = false;

//your code here

//if position to left is valid and marked

//call mousePressed for the blob on left

}

public void draw ()

{

if (marked)

fill(50);

else

fill( 255 );

rect(x, y, width, height);

fill(0);

}

}

110

  • Copy the code on this slide (#90) into Processing
  • Replace the comments on lines 49-51 with an if statement so that if there is a valid position on the left and the blob to the left is marked, mousePressed is recursively called for the blob to the left
  • Hint: what’s to the left of blobs[r][c]?

111 of 163

marked vs clicked

111

  • The MSButton class has two boolean member variables

112 of 163

contains

  • Returns true or false if an ArrayList or String contains an element.
  • Good for eliminating duplicate values

ArrayList <Integer> arlist =

new ArrayList <Integer>();

arlist.add(3);

System.out.println(arlist.contains(2));

arlist.add(2);

System.out.println(arlist.contains(2));

System.out.println(arlist);

112

113 of 163

contains

  • Returns true or false if an ArrayList or String contains an element.
  • Good for eliminating duplicate values

ArrayList <Integer> arlist =

new ArrayList <Integer> ();

arlist.add(3);

System.out.println(arlist.contains(2));

arlist.add(2);

System.out.println(arlist.contains(2));

System.out.println(arlist);

113

114 of 163

contains

  • Returns true or false if an ArrayList or String contains an element.

String str = new String("The best thing about a boolean is even if you are wrong, you are only off by one.");

System.out.println(str.contains("worst"));

System.out.println(str.contains("best"));

System.out.println(str.contains("z"));

114

115 of 163

contains

  • Returns true or false if an ArrayList or String contains an element.

String str = new String("The best thing about a boolean is even if you are wrong, you are only off by one.");

System.out.println(str.contains("worst"));

System.out.println(str.contains("best"));

System.out.println(str.contains("z"));

115

116 of 163

Checking if it doesn’t contain something

  • Often, you want to know if the ArrayList doesn’t contain a value

ArrayList <Integer> arlist =

new ArrayList <Integer> ();

arlist.add(1);

arlist.add(2);

if(!arlist.contains(3)) //doesn’t contain 3

arlist.add(3);

System.out.println(arlist);

116

117 of 163

Checking if it doesn’t contain something

  • Often, you are more interested if the ArrayList doesn’t contain a value

ArrayList <Integer> arlist =

new ArrayList <Integer> ();

arlist.add(1);

arlist.add(2);

if(!arlist.contains(3)) //doesn’t contain 3

arlist.add(3);

System.out.println(arlist);

117

118 of 163

Practice Quiz Question:�Find the output

int [] array = {4,-2,4,3,7,-2,4,6};

ArrayList <Integer> arlist =

new ArrayList <Integer> ();

for(int i = 0; i < array.length; i++)

if(!arlist.contains(array[i]))

arlist.add(array[i]);

System.out.println(arlist);

118

119 of 163

119

  • Replace the comments on lines 49-51 with an if statement so that if there is a valid position on the left and the blob to the left is marked, recursively call mousePressed for the blob to the left

120 of 163

120

  • Replace the comments on lines 49-51 with an if statement so that if there is a valid position on the left and the blob to the left is marked, recursively call mousePressed for the blob to the left
  • How would you check if there is a valid position on the left?
  • How would you check if the blob to the left is marked?
  • How would you call mousePressed for the blob to the left?

121 of 163

What is the output?

public void setup() {

Thingy bob = new Thingy(5);

Thingy notBob = new Thingy(7);

bob.mystery();

}

class Thingy {

private int myNum;

public Thingy(int n) {

myNum = n;

}

public void mystery() {

System.out.println(myNum);

}

}

121

122 of 163

this

  • means "the object in front of the dot"

public void setup() {

Thingy bob = new Thingy(5);

Thingy notBob = new Thingy(7);

bob.mystery();

}

class Thingy {

private int myNum;

public Thingy(int n) {

myNum = n;

}

public void mystery() {

System.out.println(this.myNum);

}

}

122

123 of 163

this

  • means "the object in front of the dot"

public void setup() {

Thingy bob = new Thingy(5);

Thingy notBob = new Thingy(7);

bob.mystery();//displays 5

}

class Thingy {

private int myNum;

public Thingy(int n) {

myNum = n;

}

public void mystery() {

System.out.println(this.myNum);

}

}

123

124 of 163

this

  • Now, in this particular case, this isn't necessary

public void mystery() {

System.out.println(this.myNum);

}

  • Could be replaced with just

public void mystery() {

System.out.println(myNum);

}

124

125 of 163

public void setup() {

Thingy bob = new Thingy(5);

Thingy notBob = new Thingy(7);

bob.mystery();

}

class Thingy {

private int myNum;

public Thingy(int n) {

myNum = n;

}

public void mystery() {

System.out.println(this);

}

public String toString(){

return "My number is " + myNum;

}

}

125

  • Sometimes however, the is no other way to write the code

126 of 163

System.out.println(this);

  • is the same as

System.out.println(this.toString());

126

  • Remember that in Java, sending an object to System.out.println or System.out.print automatically calls toString()

127 of 163

  • Because this is used as an argument, there is no other way to get the code to work

public void setup() {

Thingy bob = new Thingy(5);

Thingy notBob = new Thingy(7);

bob.mystery();

}

class Thingy {

private int myNum;

public Thingy(int n) {

myNum = n;

}

public void mystery() {

System.out.println(this);

}

public String toString(){

return "My number is " + myNum;

}

}

127

128 of 163

  • bob doesn't work. bob is out of scope.

public void setup() {

Thingy bob = new Thingy(5);

Thingy notBob = new Thingy(7);

bob.mystery();

}

class Thingy {

private int myNum;

public Thingy(int n) {

myNum = n;

}

public void mystery() {

System.out.println(bob); //ERROR!

}

public String toString(){

return "My number is " + myNum;

}

}

128

129 of 163

this

  • is a Java keyword (it has particular meaning in Java)
  • means "the object in front of the dot" or "the object that called the function" e.g. bob.mystery();
  • Good style: Should be used only rarely, only use this when you are required to
  • Is only required when you need to pass the object that called the function as an argument e.g.

System.out.println(this);

129

130 of 163

2 Part Practice Quiz Question:�A. Find the output�B. Identify which two uses of this are unnecessary

130

public void setup() {

WhatsIt bob = new WhatsIt('a', 1);

WhatsIt notBob = new WhatsIt('b', 2);

notBob.mystery();

}

class WhatsIt {

private char myChar;

private int myNum;

public WhatsIt(char c, int n) {

myChar = c;

myNum = n;

}

public void mystery() {

System.out.println("char is " + this.myChar);

System.out.println(this);

}

public String toString(){

return "number is " + this.myNum;

}

}

131 of 163

In Class:

  • Write a small program in processing that uses nested loops to produce the following output

Use appropriate variable names in your loops like row and col

131

132 of 163

"\t" is tab

  • Write a small program in processing that uses nested loops to produce the following output

(5,0) (5,1) (5,2) (5,3) (5,4) (5,5) (5,6) (5,7)

You may find this helpful:

System.out.print("("+row +","+col+")"+"\t");

132

133 of 163

133

134 of 163

134

Nested loops and graphics

  • Let's say I wanted to make a grid of circles that looked like this
  • I can tell it has 8 rows and 6 columns
  • So I'll need appropriate loops

135 of 163

135

One loop will make the x coordinates and the other the y

for( ?? ) //8 rows

{

for( ?? ) //6 columns

{

ellipse(x,y,5,5);

}

}

136 of 163

136

If I move down one row, what's changing, x or y?

for( ?? ) //8 rows

{

for( ?? ) //6 columns

{

ellipse(x,y,5,5);

}

}

137 of 163

137

The outer loop changes y and the inner loop changes x

for(int y = ?? ; y <= ?? ; y ?? ) //8 rows

{

for(int x = ?? ; x <= ?? ; x ?? //6 columns

{

ellipse(x,y,5,5);

}

}

138 of 163

138

The outer loop changes y and the inner loop changes x

for(int y = 10 ; y <= 80 ; y +=10 ) //8 rows

{

for(int x = 20 ; x <= 70 ; x +=10 //6 columns

{

ellipse(x,y,5,5);

}

}

139 of 163

139

The outer loop changes y and the inner loop changes x

for(int y = 10 ; y <= 80 ; y +=10 )

//8 rows at 10 20 30 40 50 60 70 80

{

for(int x = 20 ; x <= 70 ; x +=10

//6 columns at 20 30 40 50 60 70

{

ellipse(x,y,5,5);

}

}

140 of 163

140

Practice Quiz Question

  • Write a program using nested loops that will create a similar pattern of ellipses

141 of 163

Practice Quiz Question

import de.bezier.guido.*;

private Blob[][] blobs;

public final static int NUM_ROWS = 15;

public final static int NUM_COLS = 12;

void setup ()

{

size(400, 400);

// make the manager

Interactive.make( this );

blobs = new Blob[NUM_ROWS][NUM_COLS];

for(int r = 0; r < NUM_ROWS; r++)

for(int c = 0; c < NUM_COLS; c++)

blobs[r][c] = new Blob(r,c);

}

void draw(){}//empty

public class Blob

{

private int myRow, c;

private float x,y, width, height;

private boolean marked;

public Blob ( int rr, int cc )

{

width = 400/NUM_COLS;

height = 400/NUM_ROWS;

myRow = rr;

c = cc;

x = c*width;

y = myRow*height;

marked = Math.random() < .5;

Interactive.add( this ); // register it with the manager

}

public boolean isMarked()

{

return marked;

}

public boolean isValid(int row, int col)

//post condition: returns true if both row and col are valid, false otherwise

{

//your code here

return false;

}

public void mousePressed ()

{

if(marked == true)

{

marked = false;

if(isValid(myRow,c-1) && blobs[myRow][c-1].isMarked())

blobs[myRow][c-1].mousePressed();

//3 more recursive calls

}

}

public void draw ()

{

if (marked)

fill(50);

else

fill( 255 );

rect(x, y, width, height);

fill(0);

}

}

141

  • Copy the code on the right into processing
  • On line 42 add code to complete the isValid function
  • On line 53 add 3 recursive calls to the mousePressed function
  • The finished program should remove marked blobs up, down, left and right
  • On lines 3 and 4 change the number of rows and columns, and check to see that your program still works correctly

142 of 163

The call to isValid is first

  • Note that we call isValid() first before the calls to isMarked() and mousePressed()
  • If isValid() returns false, the other code won’t be executed
  • That is an example of short circuit evaluation

142

143 of 163

Constants are public, final and static

  • If you think of variables as boxes, constants are locked boxes
  • The value of a constant cannot be changed

public final static int SOME_CONSTANT = 5;

public void setup() {

//java code not shown

}

143

144 of 163

Constants are public, final and static

  • public means available in the entire program

public final static int SOME_CONSTANT = 5;

public void setup() {

//java code not shown

}

144

145 of 163

Constants are public, final and static

  • final means “locked”

public final static int SOME_CONSTANT = 5;

public void setup() {

//java code not shown

}

145

146 of 163

Constants are public, final and static

  • static means “only one” (more on this later)

public final static int SOME_CONSTANT = 5;

public void setup() {

//java code not shown

}

146

147 of 163

Constants are public, final and static

  • int is the type of constant

public final static int SOME_CONSTANT = 5;

public void setup() {

//java code not shown

}

147

148 of 163

Constants are public, final and static

  • SOME_CONSTANT is the name

public final static int SOME_CONSTANT = 5;

public void setup() {

//java code not shown

}

148

149 of 163

Constants are public, final and static

  • Here is a simple Thingy class

149

150 of 163

Constants are public, final and static

  • And here are a couple instances of the Thingy class
  • What’s the output?

150

151 of 163

Constants are public, final and static

  • And here are a couple instances of the Thingy class
  • What’s the output?

151

152 of 163

Constants are public, final and static

  • Now let’s change num to be static

152

153 of 163

Constants are public, final and static

  • When I run the same program again, the output is 3!

153

154 of 163

Constants are public, final and static

  • A static variable is shared by all instances of the class

154

bob

notBob

2

155 of 163

Constants are public, final and static

  • A static variable is shared by all instances of the class

155

bob

notBob

3

156 of 163

Constants are public, final and static

  • Since there is only one static variable that is shared by all instances of the class, it doesn’t matter if I use bob.num notBob.num or even Thingy.num

156

157 of 163

A common beginner mistake

  • Can you spot the common mistake beginning programmers often make?

157

158 of 163

A common beginner mistake

  • Unfortunately, beginning programers don’t understand the “Cannot make a static reference” error message

158

159 of 163

static variables and functions

  • static variables and functions are “shared”
  • Only one variable and/or function is shared by all instances of the class
  • static avoids unnecessary duplicates

159

160 of 163

static variables and functions

  • Constants are usually static because they only store a single value
  • static functions don’t use member variables

160

161 of 163

Practice Quiz Question:�Which line will cause an error?

Thingy bob = new Thingy();

bob.num = 6;

Thingy sam = new Thingy();

sam.num = 7;

  1. System.out.println(bob.getNum());
  2. System.out.println(sam.getNum());
  3. System.out.println(Thingy.getNum());
  4. System.out.println(bob.addNums(3,4));
  5. System.out.println(sam.addNums(5,6));
  6. System.out.println(Thingy.addNums(2,-2));
  7. System.out.println(bob.E);
  8. System.out.println(sam.E);
  9. System.out.println(Thingy.E);

161

162 of 163

for each loops & 2D arrays

  • Note that each row is a char[] character array

char [][] alphabet ={

{'a','b','c','d','e','f','g'},

{'h','i','j','k','l','m','n'},

{'o','p','q','r','s','t','u'},

{'v','w','x','y','z'}

};

for(char[] row: alphabet)

for(char letter: row)

System.out.print(letter);

162

163 of 163

In class: Modify your previous program to display the x coordinate of the last button that was clicked

  • Hint: On the third line of your program create a private float theX
  • In mousePressed set theX to the x coordinate

163