Array:got confuse with same variable one used with [ ] and one as ordinary

edited October 2015 in Programming Questions

In the processing handbook Ex_08 Unit 36 Typography I got confused with the use of currentLetter in draw

// Each letter enters from the bottom in sequence and

// stops when it reaches its destination

PFont font;

String word = "rise";

char[] letters;

float[] y; // Y-coordinate for each letter

int currentLetter = 0; // Letter currently in motion

void setup() {

  size(100, 100);

  font = loadFont("EurekaSmallCaps-36.vlw");

  textFont(font);

  letters = word.toCharArray();

  y = new float[letters.length];

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

    y[i] = 130; // Position off the screen
  }
  fill(0);
}

void draw() {
  background(204);
  if (y[currentLetter] > 35) {    
    y[currentLetter] -= 3; // Move current letter up
  } else {
    if (currentLetter < letters.length - 1) {
     
     currentLetter++; // Switch to next letter
     
    }
  }
// Calculate x to center the word on screen
  float x = (width - textWidth(word)) / 2;
  for (int i = 0; i < letters.length; i++) {
    text(letters[i], x, y[i]);
    x += textWidth(letters[i]);
  }
}

why did in draw if (y[currentLetter] > 35) stored the value of 130 I thought it is for y[i] currentLetter is 0 right ? how is that possible I seem not understand why putting [] in currentLetter became 130 ?

Answers

  • edited October 2015

    I seem to get confused now I think I get it...since currentLetter is 0 that means it is [ 0 ] that calls 130 in the y[i] setup .... welp hope is correct :(

  • edited October 2015
    • We can say arrays store values of 1 type under the same variable name.
    • In order to access a particular stored value, we need its index.
    • We specify the index via the [] access operator:
      https://Processing.org/reference/arrayaccess.html
    • As you realized by now, that index can also be any variable, expression or some value returned from a function call.
    • That is, as long it is of a whole datatype like int for example, it can be used inside [].

    P.S.: long & Long are the only integral datatype exceptions for [] indices! 8-X

Sign In or Register to comment.