Array very basic assignment question

edited September 2015 in Questions about Code
float[] s = new float[width];
float sx = 20;

for (int i = 0; i < width; i+= sx) {
    s[i] = i;
}

for (int i = 0; i < s.length; i++) {
    ellipse(s[i],20,20,20);
}

this will work will show 5 circles

but then why if i put that inside draw() or setup() it give an ArrayIndexOutofBoundsException:0

float[] s = new float[width];

void setup(){
}

void draw(){
  float sx = 20;
  for (int i = 0; i < width; i+= sx) {
    s[i] = i;
  }
  for (int i = 0; i < s.length; i++) {
    ellipse(s[i],20,20,20);
  }
}

ArrayIndexOutofBoundsException:0

Answers

  • edited September 2015 Answer ✓

    http://forum.processing.org/two/discussion/8045/how-to-format-code-and-text

    • 1st code uses the "immediate" mode. It got no setup() nor draw() and no other defined functions.
    • 2nd code is a regular full sketch. It got at least 1 setup() or 1 draw() or both.
    • System vars width, height & sketchPath aren't still initialized until code reaches setup() though.
    • Therefore at float[] s = new float[width];, s[] is an array of length = width = 0! @-)
  • _vk_vk
    edited September 2015 Answer ✓

    width is not known until setup() is run, unless there is no setup() then the pre processor will run a basic default setup() behind the scene setting width to 100. Thus your first code works

    When you add setup() and don't specify a size() it will set width to 100 as well, but it can't be accessed before setup(), so

    float[] s = new float[width];// width is 0 here...
    void setup(){}
    

    That line before setup will fail to properly initialize the array, hence the "OutOfBounds"

    You can split declaration and initialization to make this work, like:

    float[] s  ;//declare global so can be accessed in draw
    
    void setup() {
      s = new float[width];//init after width has a value
    }
    
    void draw() {
    
      float sx = 20;
      for (int i = 0; i < width; i+= sx) {
        s[i] = i;
      }
      for (int i = 0; i < s.length; i++) {
        ellipse(s[i], 20, 20, 20);
      }
    } 
    
  • _vk_vk
    Answer ✓

    ops... late :)

  • welp,thats a no brainer have not thought about it thanks

Sign In or Register to comment.