Use random() in static method

I have a static method where I would like to use the random function, however, I get the error

Cannot make a static reference to the non-static method random(float) from the type PApplet

I’ve tried to google for the error but kept finding stuff that was related to calling your own methods, rather than the built-in methods.

How can I get random numbers in processing from a static method?

1 Like

You can directly call Java’s own random():
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#random()

Or you can create static wrapper functions which forward call PApplet’s methods:
Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html#random-float-float-

static final float random(final PApplet p, final float high) {
  return p.random(high);
}

static final float random(final PApplet p, final float low, final float high) {
  return p.random(low, high);
}

But as you can see above, we have to pass the sketch’s PApplet reference for such wrapper approach.

1 Like