将随机数的 return 值存储为局部变量?

Storing the return value of a random number as a local variable?

所以我正在通过创建口袋妖怪战斗模拟器(使用 JOption 面板)来练习基本 Java。

我正在使用以下方法将神奇宝贝的攻击值作为最大值,并为简单起见将最小值设置为 0。

public static int randomDamage(int min, int max) {
    int range = (max - min) + 1;
    int randomDamage =  (int)(Math.random() * range) + min;
    return randomDamage;

这是我调用方法的地方。

public static void battle(Pokemon pokemon1, Pokemon pokemon2) {
    showMessageDialog(null, pokemon2.name + "'s stats are: \n Health: "
            + pokemon2.health + "\n Attack: " + pokemon2.attack + "\n Speed: " + pokemon2.speed);
    showMessageDialog(null, pokemon1.name + " begins the fight against " + pokemon2.name);
    do {

        if (pokemon1.health > 0 && pokemon2.health > 0) {
            showMessageDialog(null, pokemon1.name + " attacks " + pokemon2.name);
            pokemon2.health = pokemon2.health - randomDamage(0,pokemon1.attack);
            showMessageDialog(null, pokemon1.name + " does " + pokemon1.randomDamage + " damage to " +
                    pokemon2.name + " and " + pokemon2.name + " has " + pokemon2.health + " left.");
        }

        if (pokemon1.health > 0 && pokemon2.health > 0) {
            showMessageDialog(null, pokemon2.name + " attacks " + pokemon1.name);
            pokemon1.health = pokemon1.health - pokemon2.attack;
            showMessageDialog(null, pokemon2.name + " does " + pokemon2.attack + " damage to " +
                    pokemon1.name + " and " + pokemon1.name + " has " + pokemon1.health + " left.");
        }


    } while (pokemon1.health > 0 && pokemon2.health > 0);
    if (pokemon1.health < 1) showMessageDialog(null, pokemon1.name + " has been reduced to 0 health. "
            + pokemon1.name + " has lost the fight.");
    else showMessageDialog(null, pokemon2.name + " has been reduced to 0 health. "
            + pokemon2.name + " has lost the fight.");

}

伤害似乎是随机的,正如我预期的那样,但它总是说 "Charmander does 0 damage to Rattata and Rattata has x health left"。

是否可以从生命值中减去 randomDamage 值,然后在我的 JOption 中显示该值 window?

谢谢!

如果你想多次使用它,你需要先存储 randomDamage 的 return 值(即在 pokemonX.randomDamage 中)。

示例(假设 Pokemon 有一个 int randomDamage 成员):

pokemon1.randomDamage = randomDamage(0,pokemon1.attack);
pokemon2.health = pokemon2.health - pokemon1.randomDamage;
showMessageDialog(null, pokemon1.name + " does " + pokemon1.randomDamage + " damage to " + pokemon2.name + " and " + pokemon2.name + " has " + pokemon2.health + " left.");