Looping through an array?

Normally I would say there isn’t much more to it than using modulo – so no need, your “class” is int idx, its “next” method is idx=(idx+1)%arr.length, and that’s it.

However, Java’s % is actually the remainder, which causes a gotcha on negatives, so IF you ever wanted to step negative numbers then it might be useful to wrap a loop counter in a method or class.

/**
 * LoopCounter
 * https://discourse.processing.org/t/looping-through-an-array/13078/19
 **/
void setup() {
  LoopCount lc = new LoopCount(4);
  println(lc.val);
  println(lc.inc(1), lc.inc(1), lc.inc(1), lc.inc(1));
  println(lc.inc(2), lc.inc(2));
  println(lc.inc(7));
  println(lc.inc());
  println(lc.dec(), lc.dec(), lc.dec(), lc.dec());
  println(lc.dec(7));
}

class LoopCount {
  int max;
  int val;
  LoopCount(int max) {
    this.max = max;
  }
  LoopCount(int max, int val) {
    this.max = max;
    this.val = val;
  }
  int dec() {
    return inc(-1);
  }
  int dec(int count) {
    return inc(-count);
  }
  int inc() {
    return inc(1); 
  }
  int inc(int count) {
    this.val = ((val+count)%max + max)%max;
    return this.val;
  }
}

Output:

0
1 2 3 0
2 0
3
0
3 2 1 0
1