0

I am making a small RPG using Jcreator.

I give whatever character you pick damage at the start, we will take the Swordsman as an example.

I gave him 10 Damage and for the hitting damage I made the int Hit.

My problem is that this random number is not working well for damage as it is giving me damage under the actual attack range.

Hit = 1 + (int) ((Math.random() * (Damage - 1)) +1);
Nick Meyer
  • 1,661
  • 1
  • 14
  • 26
user3670236
  • 113
  • 1
  • 1
  • 12
  • 1
    I can't comprehend what you're asking here... random() * Damage will, by definition, result in a value less than Damage. – Yeraze Sep 06 '14 at 02:25
  • 1
    Do you want 10 to be the minimum damage, and have a chance to get higher? – Shadow Sep 06 '14 at 02:26
  • No 10 is the average damage,I Want 5 more and 5 less,I Havent programmed in a while so im kind of shaky – user3670236 Sep 06 '14 at 02:29
  • @user3670236 To clarify, you have `int` `Damage` equal to `10`, and you want `Hit` to be within the range of `5 - 15`; do you want the range in general to be from `Damage/2` to `3 * Damage/2`? Or do you want the range to be from `Damage - 5` to `Damage + 5`? Like, if `Damage` was 20, would you want the range to be `10 - 30` or `15 - 25`? – Nick Meyer Sep 06 '14 at 02:34
  • use nextInt from java.util.Random http://ideone.com/AyyTHB – d0c Sep 06 '14 at 02:35
  • possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – Nick Meyer Sep 06 '14 at 02:39
  • Thank you for all the help guys,i understand random number generators a bit better now ^^ – user3670236 Sep 06 '14 at 02:47

3 Answers3

1

You need to always know the bounds of your random number generator.

In pseudocode, to generate a number from a random space with a minimum and maximum,

Result = Minimum + (Maximum - Minimum) * (Random() - RandMin) / (RandMax - RandMin)
Gutblender
  • 1,290
  • 12
  • 24
1

Try this:

hit = (int)(Math.random() * range) + min;

where range = the max value you want minus the min value you want, i.e.,

int range = (max - min) + 1;     
user1790252
  • 486
  • 5
  • 13
0

Something like the following should work, and give you a number in the range of 5 above or below your damage:

randomNum = Damage-5 + (int)(Math.random()*Damage+1);

I tested it and it seems to have worked for me, didn't get a number below 5 or greater than 15

Shadow
  • 3,666
  • 4
  • 17
  • 40