我正在试图弄清楚如何将选择的对象随机化为方法中的参数。所以我在下面创建了两个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);
}
}
答案 0 :(得分:2)
重要提示:通常不建议对模型使用静态方法和静态字段
相反,你应该创建一个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());
答案 1 :(得分:0)
使用对象的数组(或列表)并随机生成索引值。
public class PokemonTester{
public static void main(String[] args){
WildPokemon[] pokemons = { rattata, pidgey };
Pokemon.battle(starter, pokemons[ (int)(Math.random()*pokemons.length) ] );
}
}