We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, I am trying to iterate through a list of particles to apply later some motion to them, the first one must remain static. I´ve thought about using both enhanced and 'classic' for loop; the first one was rejected, since it iterates through all elements of the array, while the second one throws an "indexOutOfBoundsException;index:4,Size:4" It seems to be a very naive solution but I haven´t figure it out yet; is there something I am missing or any other more suitable loop I could go through? Thanks for answers. Here is part of the code:
Constructor(){
//blabla
..
Particle first=particles.get(0);
first.lock();
//blabla
..
}
void display() {
//blabla
..
//for (Particle p : particles) { //rejected
for (int i = particles.size();i>=1; i++) {//we start from i>=1 so 1st particle remains fixed ??
Particle p= particles.get(i);
//blabla
ellipse(p.x, p.y, 2, 2);
..
}
Answers
first item is list[0] so just start the loop at i = 1
I feel stupid now,, #:-S thanks koogs!
The reason this line:
for (int i = particles.size();i>=1; i++) {
doesn't work is that you start withi
atparticles.size()
but if particles.size() was for example 4 then the indices would be 0, 1, 2 and 3 so if you would try to get element 4 you get an error. Usingfor (int i = particles.size()-1;i>=1; i--)
should work, going fromparticles.size()-1
.For backwards loop, my favorite template is:
for (int i = particles.size(); i-- != 0;) {}
*-:)@colouredmirrorball: I tried that line of code
for (int i = particles.size()-1;i>=1; i++) {
following the same thinking.. but got the same "indexOutOfBoundsException;index:4,Size:4" error message.@GoToLoop: with this structure the paticle 0 is not static and responds to the whole motion applied later to the array. As it did with the enhanced for loop.
thanks both for the alternatives!
Like I said that was my template. Since you don't want index
0
, it gotta be stopped after index1
in your case:for (int i = particles.size(); i-- > 1;) {}
oh, I misunderstood you then,, yeah that works too :)
Derp, you are right. It should be this:
for (int i = particles.size()-1;i>=1; i--) {
instead of i++, because you are going backwards through the loop. (Edited in the other post as well)
is there a short way to skip an element in the middle? something like
thank you.
@colouredmirrorball:
for (int i = particles.size()-1;i>=1; i--) {
works nicely. Sorry for late reply and thank you!