Home > Enterprise >  Why does my code sometimes set a value of 0 and loop forever?
Why does my code sometimes set a value of 0 and loop forever?

Time:06-03

I need to program a attack value for a Pokemon fight. and then I need to multiply the damage value with a number between 0 and 1, after each round, but sometimes my damage value is 0 and then it goes on forever.

How can I fix this?

the if case at the end was a try to fix the problem.

 public static void attackvalue(Taschenmonster pokemon1, Taschenmonster pokemon2) {

    double multiplier = Math.random();

    pokemon1.damage = (int) (pokemon1.damage * multiplier);
    pokemon2.damage = (int) (pokemon2.damage * multiplier);

    if (pokemon1.damage <= 45){
        pokemon1.damage = (int) (pokemon1.damage * multiplier);
    }
    if (pokemon2.damage <= 45){
        pokemon2.damage = (int) (pokemon2.damage * multiplier);
    }

}

CodePudding user response:

Issue

The following operation: pokemon1.damage * multiplier gives you a double value, if you are unlucky enough, it might results in a value in the range: [0, 1[.

Then, you are converting this value into an integer using the (int) .... This truncates away the floating part, therefore any value between 0 and 1 (excluded) are changed to 0.

Solution

To avoid this scenario, you should clamp your value in a given range, e.g.

pokemon1.damage = Math.max(10, Math.min(100, pokemon1.damage));

But the idea behind your attempt is the same, but should be more like:

if (pokemon1.damage <= 45){
        pokemon1.damage = 45;
    }

Setting value to 45 instead of re-doing the same computation as before.

CodePudding user response:

Remove the (int), it rounds your value towards 0.

If the variable damage in Taschenmonster is an int, change it to a double so that it can store floating point values (like 2.7)

Edit:

Use Math.round(...) instead of (int) ... so that if your damage results in 0.6, it will be stored as 1

  •  Tags:  
  • java
  • Related