我试图从类中创建的方法中选择一个随机方法。有没有办法创建ArrayList
并传递方法?我试图这样做,但是当我尝试将该方法添加到数组时,我收到错误。
public class Monkey{
private int energy;
String[] food = {"Meat", "Fish", "Bugs", "Grain"};
ArrayList<Activity> monkeyActivity = new ArrayList<>();
public Monkey(int energy) {
this.energy = energy;
}
public int getEnergy() {
System.out.println("Monkey energy level: " + energy);
return energy;
}
public void sound() {
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
monkeyActivity.add(sound()); //I get an error message here when trying
//to add the method to the array
}
public void play(){
if (energy >= 8){
System.out.println("Monkey begins to play.");
energy -= 8;
}else {
System.out.println("Monkey does not have enough energy to play");
}
System.out.println("Energy remaining: " + energy);
}
public void eat(){
Random random = new Random();
int index = random.nextInt(food.length);
System.out.println("Monkey beings to eat " + food[index]);
energy += 5;
System.out.println("Energy remaining: " + energy);
}
public void sleep(){
System.out.println("Monkey is sleeping: Zzz...");
energy += 10;
System.out.println("Energy remaining: " + energy);
}
}
这是我为通用Activity创建的单独类。
public class Activity {
private String sleep;
private String eat;
private String sound;
private String play;
public Activity(String sleep, String eat, String sound, String play) {
this.sleep = sleep;
this.eat = eat;
this.sound = sound;
this.play = play;
}
public String getSleep() {
return sleep;
}
public String getEat() {
return eat;
}
public String getSound() {
return sound;
}
public String getPlay() {
return play;
}
public void setSleep(String sleep) {
this.sleep = sleep;
}
public void setEat(String eat) {
this.eat = eat;
}
public void setSound(String sound) {
this.sound = sound;
}
public void setPlay(String play) {
this.play = play;
}
}
答案 0 :(得分:2)
你正在混淆概念。
public void sound() { // ... monkeyActivity.add(sound());
方法sound()
的返回值是 void (这意味着没有返回值),但是您尝试添加其(不存在的)返回值作为List的元素。这是你的编译器抱怨的。
public void sound() { System.out.println("Monkey: Oooo Oooo~!"); energy -= 3; monkeyActivity.add(sound());
在最后一行中,您执行递归调用,这意味着您调用与此代码完全相同的方法。如果这种情况无意中发生,则几乎会产生StackOverflowError
。
你有一个班级Activity
。
但是如果你仔细看看这不是单个活动(正如类名所暗示的那样),但它是所有可能的活动。
因此,您的收藏集monkeyActivity
无法将单项活动作为元素。
做一个狂野的猜测我认为你想要的更像是这样:
interface Activity{
void do();
}
public class Monkey{
private int energy;
String[] food = {"Meat", "Fish", "Bugs", "Grain"};
List<Activity> monkeyActivity = new ArrayList<>();
// ...
public void sound() {
monkeyActivity.add(new Activity(){
public void do(){
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
}
});
}
答案 1 :(得分:1)
您可以将每个方法存储为Runnable
,与任何&#34;操作&#34;是no-arg void方法,满足Runnable
功能接口:
List<Runnable> actions = Arrays.asList(this::sound, this::play, this::eat, this::sleep);
执行随机方法,只需:
Random rnd = new Random();
actions.get(rnd.nextInt(actions.size())).run();