Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the same random number

Tags:

java

random

I want to generate a random number to apply to some arrays in order to get different elements in each execution. The arrays contain names of sport products (product,size,price,etc). By doing this, I want to make random products that would go into a String, but in each execution of the program, I get the same product.

Where is the problem?

Here is the code in the class generaProductos:

public void generaProductos() {
    int num;
    for (int i=0;i<3;i++){
        num = (int) Math.random() * 3;
        String cliente = tipoProducto[num] + " " + deporte[num] + " " +
                         destinatario[num] + " " + color[num] + " " + tallaRopaAdulto[num]
                         + " " +   preciosIVA[num];
        System.out.println(cliente);
     }
     return;
 }

And here is where I call generaProductos() method in main:

switch (opt){
    case 1:
        generaProductos alm = new generaProductos();
        alm.generaProductos();

When I execute my code, I always receive this:

Botas Futbol Hombre Marron S 16.99

Botas Futbol Hombre Marron S 16.99

Botas Futbol Hombre Marron S 16.99

(In English it would be Football boots men brown size S 16.99)

like image 404
Javier.S Avatar asked Dec 23 '15 13:12

Javier.S


People also ask

Can you generate the same random numbers everytime?

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used.

Why does Rand keep giving me the same number?

This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.

Why does Rand give me the same number C++?

The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation.


2 Answers

You cast a floating point value between 0 and 1 (exclusive) to int, which results in 0, and then multiply 0 by 3, which is still 0.

change

(int) Math.random() * 3

to

(int) (Math.random() * 3)
like image 57
Eran Avatar answered Oct 12 '22 23:10

Eran


num = (int) Math.random() * 3;

will always be 0, because of order of precedence.

Math.random() is always < 1 so casting it to int will give you 0, then you multiply, still getting 0.

like image 34
zubergu Avatar answered Oct 13 '22 00:10

zubergu