gpt4 book ai didi

java - 如何随机化参数中的对象?

转载 作者:行者123 更新时间:2023-11-30 02:34:05 25 4
gpt4 key购买 nike

我试图弄清楚如何随机化在方法中选择作为参数的对象。所以我在下面创建了两个 Pokemon 类(rattata 和 pidgey)

class WildPokemon {

private static int randomHealth(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
private static int randomAttack(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
private static int randomSpeed(int min, int max) {
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}


static Pokemon rattata = new Pokemon("Rattata",randomHealth(15,20),randomAttack(2,5),randomSpeed(2,6));
static Pokemon pidgey = new Pokemon("Pidgey",randomHealth(10,17),randomAttack(3,4),randomSpeed(3,5));
}

下面我可以在 Pokemon.battle() 方法中调用rattata,并且它按预期运行。有没有办法可以将我的第二个参数随机化为随机选择的rattata或pidgey?

public class PokemonTester{

public static void main(String[] args){
Pokemon.battle(starter, WildPokemon.rattata);
}
}

最佳答案

重要提示:通常不建议在模型中使用静态方法和静态字段。
相反,您应该创建一个 WildPokemon 实例并调用它的方法。

按照与计算随机值相同的方式进行操作。
您应该使用神奇宝贝列表,而不是使用两个硬编码值进行计算。

试试这个:

public class WildPokemon{
...
private Random rand = new Random();
private List<Pokemon> pokemonList;
...
public WildPokemon(){
pokemonList = new ArrayList();
Pokemon rattata = new Pokemon("Rattata",randomHealth(15,20),randomAttack(2,5),randomSpeed(2,6));
pokemonList.add(rattata);
Pokemon pidgey = new Pokemon("Pidgey",randomHealth(10,17),randomAttack(3,4),randomSpeed(3,5));
pokemonList.add(pidgey);
...
}

private Pokemon getRandomPokemon() {
int n = rand.nextInt(pokemonList.size());
return pokemonList.get(n);
}
...
}

并称其为:

 WildPokemon wildPokemon = new WildPokemon();
Pokemon.battle(starter, wildPokemon.getRandomPokemon());

关于java - 如何随机化参数中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43549933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com