-2

I use this random number generator and it works fine but then I needed a range (e.g. 16-20) of numbers but I can't get it to work. I have no idea what to do.

for (int i = 1; i <= 1; i++) {
    int RandomAttack = (int) Math.random() * 20;
    System.out.println(RandomAttack);
}

I need the simplest code there is.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
EneioArzew
  • 58
  • 1
  • 1
  • 10

2 Answers2

2

Make sure you have your Random imported and initialised, Random random = new Random();

Follow:

int randomNumber = random.nextInt(max - min) + min;

In your case

int randomNumber = random.nextInt(20 - 16) + min;

That alone should get you your desired value within range. Don't forgot to import Java's Random class on top of your class.

Also, I'm not quite understanding the point of your loop over there. Am I missing something obvious or is that just one iteration?


Here is a class example:

import java.util.Random;

public class RandomRange {
    private static Random random;

    public static void main(String[] args) {
        random = new Random();

        System.out.println(random.nextInt(20 - 16) + 16);
    }
}
Juxhin
  • 5,068
  • 8
  • 29
  • 55
  • yeah. actually it only is one iteration because it's supposed to be like hitpoints if it were in a game. – EneioArzew Sep 28 '14 at 13:45
  • If it's basic Java then I suggest just learning the fundamentals. When creating a game you have to take into account alot of things. – Juxhin Sep 28 '14 at 13:46
  • Also don't let the `static` scare you in my variable initialisation, the `Random` object could simply be initialised within the main method – Juxhin Sep 28 '14 at 13:47
  • @JulacOntina If you're new to StackOverflow, feel free to mark any answer you feel helped you most by ticking the check sign. Thanks – Juxhin Sep 28 '14 at 19:48
2

Math.random() will only return numbers in range 0..1. You could scale this by multipling by range and adding on minimum.

Or use java.util.Random(), this has a handy method nextInt() which will return between 0 and < value.

So you need to go 0<= value < 5 to have values 0, 1, 2, 3, 4

import java.util.Random;

public class RandomTest {

    public static void main(String[] args) {
        Random random = new Random();
        for (int i = 1; i <= 10; i++) {
            int value = 16 + random.nextInt(5);
            System.out.println(value);
        }
    }

}
Adam
  • 35,919
  • 9
  • 100
  • 137