How to get a random number in a range?

2

I was wondering how you could get a random number in java within a range. The number must be a decimal number that is in a certain range, but random.

private Random random = new Random();

random.setSeed((long) (centralPoint.x*456 + centralPoint.y*456));

float num = random.nextFloat();

But with this program it gives me a completely random number, without rank.

    
asked by Pasblo 09.02.2018 в 20:13
source

2 answers

3

If you want to get a random value for a range of decimal point numbers , it's done this way:

 Random r = new Random(); 
 resultado = r.nextFloat() * (maximo - minimo) + minimo;

This is an example:

float maximo = 2.0f;
float minimo = 0.1f;
float resultado;
for (int i=0; i<100; i++){
     Random r = new Random(); 
     resultado = r.nextFloat() * (maximo - minimo) + minimo;
     System.out.println("Numero:" +resultado);
}

Online example

You can get a random value from a range of integer values like this:

   Random r = new Random(); 
   resultado = r.nextInt((maximo - minimo) + 1) + minimo;

This is an example:

int maximo = 10;
int minimo = 3;  
int resultado;
for (int i=0; i<100; i++){
     Random r = new Random(); 
     resultado = r.nextInt((maximo - minimo) + 1) + minimo;
     System.out.println("Numero:" +resultado);
}

Online example.

answered by 09.02.2018 / 20:17
source
1

Try this, it allows you to get decimal number up to 2 places after the decimal point. The 10 represents the maximum value of the range and the minimum 5, so you only have to change it according to your needs. Keep in mind the maximum value never comes out as a result.

(random.nextInt(10 - 5) + 5) + (float) (random.nextInt(100) / 100.0);
    
answered by 09.02.2018 в 20:47