Reputation:
class Scratch {
public void meth1(){
}
public void meth2(){
}
public void meth3(){
}
public void meth4(){
}
public void meth5(){
}
public static void main(String[] args) {
int randomNumber=(int)Math.random()*5;
}
}
Here I have 5 methods, and I want to call them randomly. I am new to OOP but know a bit about C, in that case I would've stored the addresses of the functions(methods) in an array, generate a random number between [0,4] and call the functions using the array in random order. But in Java, I don't know how to get the memory address of a method. How should I do that?
Upvotes: 2
Views: 481
Reputation: 4723
You do this with a "function-variable" of type Runnable
and its method Runnable#run
.
Scratch s = new Scratch();
List<Runnable> methods = new ArrayList<>();
methods.add(s::meth1); // this is how you reference a method itself
methods.add(s::meth2);
...
methods.get(1).run(); // this is how you "tell" the Runnable to execute its code
The abstract method run
is overriden with the code you have, so this is a "reference" to call your method. In the package java.util.function
you can find many classes that can be used in case your method has parameters or/and a return-value.
Now calling a random method from the list is pretty simple:
int randomNumber = new Random().nextInt(methods.size());
methods.get(randomNumber).run();
Upvotes: 5
Reputation: 2935
the easiest way would be to put your methods in a switch statement and get a random value that way:
class Scratch {
public void meth1(){
}
public void meth2(){
}
public void meth3(){
}
public void meth4(){
}
public void meth5(){
}
public static void main(String[] args) {
Random r = new Random();
Scratch scratch = new Scratch();
int num = r.nextInt(5);
switch(num) {
case 0:
scratch.meth1();
break;
case 1:
scratch.meth2();
break;
case 2:
scratch.meth3();
break;
case 3:
scratch.meth4();
break;
case 4:
scratch.meth5();
break;
}
}
}
Upvotes: 1
Reputation: 376
This is a little tedious, but you can set a certain range to a method. For example:
public static void main(String[] args) {
int rand=(int)Math.random()*5;
if(rand < 0.1) {
meth1();
} else if(rand < 0.2) {
meth2();
} else if(rand < 0.3) {
//etc...
}
}
Upvotes: 0