In Bluej Class Random IDE, limit start and end values

Asked

Viewed 123 times

0

As I have in the code gives me the error of

void cannot be deferenced

On the part of nextInt() in the last two lines and with so many attempts I’ve made I ended up like this. Latitude cannot be outside [-9.5,-6.2] degrees and 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);

1 answer

0


The mistake you make is because the method setSeed is void and so does not return any value which makes it can not do .nextInt() then on the void.

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

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

If you want the numbers to come out in a specific range you need to multiply the number that comes out by máximo-minimo and to this add the 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 the nextDouble.
  • This number is multiplied by 42.2-36.8 that gives 5.4, thus giving a number in the interval [0-5.4)
  • By adding up the minimum of 36.8 we’ll take a break from [36.8, 42.2)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.