【问题标题】:How to randomize an object in a parameter?如何随机化参数中的对象?
【发布时间】:2017-09-18 21:11:06
【问题描述】:

我试图弄清楚如何随机化选择作为方法中参数的对象。所以我在下面创建了两个 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);
    }
}

【问题讨论】:

  • 制作一个你拥有的所有口袋妖怪的数组(或列表),然后将随机位置的口袋妖怪传给战斗。
  • Math.random() > 0.5? rattata : pidgey.

标签: java object parameters


【解决方案1】:

重要说明:一般不建议对模型使用静态方法和静态字段。
相反,您应该创建一个 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());

【讨论】:

  • 你忘了list.size()list.get(n)
  • @M.普罗霍罗夫 确实,谢谢。我对所有这些静态方法和字段感到不安,这些静态方法和字段真的不建议我改变得太快:)
  • @davidxxx 对不起所有的静态废话。我正在使用这个项目自学,所以我主要只是自动填充 IntelliJ 推荐的内容。我还没有学习列表,所以我显然还有很长的路要走。感谢您的帮助!
  • @davidxxx 静态状态实际上适用于小型应用程序。建议避免它而不解释为什么在我看来更糟:它滋生了太多的误解。
  • @M.普罗霍罗夫 我不同意。在任何地方使用静态意味着使用全局变量设计您的应用程序。今天的小应用可能成为明天的中型或大应用。为应用编写不可维护且更难测试的代码永远不会很好。
【解决方案2】:

使用对象的数组(或列表)并随机生成索引值。

public class PokemonTester{

    public static void main(String[] args){
        WildPokemon[] pokemons = { rattata, pidgey };
        Pokemon.battle(starter, pokemons[ (int)(Math.random()*pokemons.length) ] );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多