5

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)

3 Answers 3

10

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)
6
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.

0

You can use Math Library of java to generate Random Integers. If you use Math.random() then you will get random number only within 0.0 to 0.1

If you want to take random integers between large range of integers then you can use following function by providing two integer inputs i.e. Min & Max No.

public static int RandInt(int max, int min){
    return ((int) (Math.random()*(max - min))) + min;
}
3
  • I think you mean that Math.random() would give a random number between 0 and 1
    – user007
    Dec 24, 2015 at 8:27
  • Yes.. The Math.random() of lang package in java returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0
    – Rish
    Dec 24, 2015 at 10:45
  • Then probably you want to correct that in your answer!
    – user007
    Dec 24, 2015 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.