In BlueJ Class Random IDE, limit the initial and final values

0

As I have in the code gives me the error of

  

void can not be deferenced

In the part of nextInt() in the last two lines and with so many attempts I've already done I ended up staying like this. The latitude can not be outside [-9.5, -6.2] degrees and the longitude [36.8.42.2]

Random randomLongitude = new Random(); 
Random randomLatitude= new Random();
randomLatitude.setSeed((long)-9.5).nextInt((int)-6.2);        
randomLongitude.setSeed((long)36.8).nextInt((int)42.2);
    
asked by anonymous 29.01.2018 / 02:00

1 answer

0

The error you get is because the setSeed method is void and therefore does not return any value which means that you can not .nextInt() then void .

randomLatitude.setSeed((long)-9.5).nextInt((int)-6.2);
//---------------------------------^ aqui

This setSeed method is used to define the random start point, also called random seed. It is useful only when you want to be able to reproduce certain random outputs in a deterministic way. In your case you also do not need to create two Random objects because with only one you can generate as many random numbers as you like.

If you want the numbers to go out at a specific interval, you need to multiply the number that exits by máximo-minimo and then add minimo :

Random random = new Random(); 
double randomLongitude = random.nextDouble() * (42.2-36.8) + 36.8;

Analyzing this last line we see that:

  • A number is generated in the range [0,1) with nextDouble .
  • This number is multiplied by% with% of% giving 42.2-36.8 , thus giving a number in the range 5.4
  • When we add the minimum of [0-5.4) we get the interval of 36.8

You can even create a function to simplify:

static Random random = new Random();

public static double aleatorioEntre(double min, double max){
    return random.nextDouble() * (max-min) + min;
}

public static void main(String[] args) {
    double randomLatitude = aleatorioEntre(-9.5, -6.2);
    double randomLongitude = aleatorioEntre(36.8, 42.2);
}

See this example working on Ideone

    
29.01.2018 / 02:45