Reputation: 99
I want to choose a function randomly. This is the following code:
public class Thank_you_five implements RandomInterface
{
public static void Thankyou_five(){...}
}
public class Thank_you_four implements RandomInterface
{
public static void Thankyou_four(){...}
}
public class Thank_you_three implements RandomInterface
{
public static void Thankyou_three(){...}
}
public interface RandomInterface
{
public static void Thankyou_five();
public static void Thankyou_four();
public static void Thankyou_three();
}
So my goal here is to pick a function randomly, like in python we random.choose() and some function inside, I want to achieve the same with Java
Please help.
Thanks, Adrija
Upvotes: 1
Views: 2226
Reputation: 121669
Frankly, I like Ruslan's suggestion better. But as long as you ask, this is along the lines of what I was thinking:
package com.example;
import java.util.Random;
public abstract class RandomFn {
public static RandomFn factory() throws Exception {
int r = new Random().nextInt(3);
switch (r) {
case 0: return new ThankYouOne();
case 1: return new ThankYouTwo();
case 2: return new ThankYouThree();
default : throw new Exception ("ThankYou(" + r +"): unsupported value!");
}
}
public abstract void thankYou();
public static void main(String[] args) {
try {
RandomFn.factory().thankYou();
} catch (Exception e) {
System.out.println(e);
}
}
}
class ThankYouOne extends RandomFn {
public void thankYou() {
System.out.println("Thank you one");
}
}
class ThankYouTwo extends RandomFn {
public void thankYou() {
System.out.println("Thank you two");
}
}
class ThankYouThree extends RandomFn {
public void thankYou() {
System.out.println("Thank you three");
}
}
If you don't like the idea of many classes, then
public class RandomFn {
public void thankYou () throws Exception {
int r = new Random().nextInt(3);
switch (r) {
case 0:
thankYouOne(); break;
case 1:
thankYouTwo(); break;
case 2:
thankYouThree(); break;
default :
throw new Exception ("ThankYou(" + r +"): unsupported value!");
}
}
private void thankYouOne() { System.out.println("Thank you one"); }
private void thankYouTwo() { System.out.println("Thank you two"); }
private void thankYouThree() { System.out.println("Thank you three"); }
...
Upvotes: 2
Reputation: 6290
First of all it would be probably better to define one abstarct method inside interface:
public interface RandomInterface{
void thankYou();
}
Then you can create several implementations:
RandomInterface t1 = () -> System.out.println("thank you 1");
RandomInterface t2 = () -> System.out.println("thank you 2");
RandomInterface t3 = () -> System.out.println("thank you 3");
To get random implementation you can add all objects to array and generate random index:
RandomInterface[] arr = {t1, t2, t3};
int i = new Random().nextInt(arr.length);
arr[i].thankYou();
Upvotes: 7