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

时间:2017-04-21 15:27:01

标签: java variables random methods local

所以我通过创建一个口袋妖怪战斗模拟器(使用JOption Panes)练习基本Java。

我使用以下方法将Pokemon的攻击值作为最大值,并将min设置为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对Rattata造成0点伤害,而Rattata对x生命有效”。

是否可以从运行状况中减去randomDamage值,然后在JOption窗口中显示该值?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您想多次使用它,则需要先存储randomDamage的返回值(即在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.");