我试图从类内创建的方法中选择一个随机方法。有没有办法创建 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;
}
}
最佳答案
你混淆了概念。
技术问题:
返回值冲突
public void sound() { // ... monkeyActivity.add(sound());
您的方法 sound()
的返回值是 void(这意味着无返回值),但您尝试添加其 (不存在)将值作为元素返回到列表。这就是你的编译器所提示的。
意外递归
public void sound() { System.out.println("Monkey: Oooo Oooo~!"); energy -= 3; monkeyActivity.add(sound());
在最后一行中,您执行了一个递归调用,这意味着您调用了与此代码所在的完全相同的方法。如果这种情况意外发生,则几乎会导致 StackOverflowError
.
在没有适当分析的情况下编写类
您有一个类Activity
。
但如果您仔细观察,这不是一个单个 Activity (正如类名称所暗示的那样),而是所有可能的 Activity 。
因此,您的集合 monkeyActivity
无法将单个 Activity 作为元素保存。
大胆猜测,我认为你想要的更像是这样的:
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;
}
});
}
关于java - 从多种方法中选择随机方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48036163/