Processing Basics - 9. Array

我们已经学过编程中许多基本的概念啦,比如 variables, conditionals, loops, objects, functions 等,那么今天我们要学习最后一个基本的概念——Array!有木有非常鸡冻~

9.1 what is an Array?

two important questions:

  • what is an array?
    A List of Data (100 bubbles)
    an Array is a data structure

int: a single number
Value: a continuous list of numbers

declaretion:
int[ ] = { 3, 5, 6, 7, 8 }

  • why do we need an array?

9.2 Declare, Initialize, and Use an Array

PROCESS:

1. declare a variable

1a. create an array (how many spots)

e.g.:

int[] nums = new int[ 10 ];
  • int - type of the array
    [] - indicating it's an array
    nums - name of the array
    10 - how long

the default value for an integer: 0

2. Initialize

  • very important below:
    10 spots
    index 0 to 9
num[0] = -3;
num[4] = 132;
point(num[1],num[3]);

3. Use

exercise: replace int with bubble

9.3 Array of Objects

Replace Objects with an Array:

Bubble[] bubbles = new Bubble[2];

void setup() {
  size(640, 360);
  bubbles[0] = new Bubble(64);
  bubbles[1] = new Bubble(64);
}

void draw() {
  background(255);
  bubbles[0].ascend();
  bubbles[0].display();
  bubbles[0].top();

  bubbles[1].ascend();
  bubbles[1].display();
  bubbles[1].top();
}

9.4 Arrays and Loops

Replace hard coding with "for loop":

Bubble[] bubbles = new Bubble[25];

void setup() {
  size(640, 360,P2D);
  for (int i = 0; i < bubbles.length; i ++) {
    bubbles[i] = new Bubble(i*4);
 // bubbles[i] = new Bubble(random(60));
  }
}

void draw() {
  background(255);
  for (int i = 0; i < bubbles.length; i ++) {
    bubbles[i].ascend();
    bubbles[i].display();
    bubbles[i].top();
  }
}

9.5 Arrays of Flexible Size

limitations:fixed number of an array

strategies:ArrayList

Bubble[] bubbles = new Bubble[100];
int total = 0;
void setup() {
  size(640, 360, P2D);
  for (int i = 0; i < bubbles.length; i ++) {
    //bubbles[i] = new Bubble(i*4);
    bubbles[i] = new Bubble(random(60));
  }
}

void mousePressed() {
if( total < 25){
  total = total + 1;
} else {
total = 0
}
}

void keyPressed() {
  total = total - 1;
}

void draw() {
  background(255);
  for (int i = 0; i < total; i ++) {
    bubbles[i].ascend();
    bubbles[i].display();
    bubbles[i].top();
  }
}
  1. what do you do when total gets to 100?
  2. add below to "bubble" tab:
boolean active = false;

ps:

  1. This video discusses the inevitable quandary of what to do when you want to resize your array dynamically while a program is running.
  2. For ArrayLists, check out this video in nature of code.

你可能感兴趣的:(Processing Basics - 9. Array)