Getting the same random number

I want to create a random number to apply to some arrays in order to get different elements in each execution. Arrays contain the names of sports products (product, size, price, etc.). By doing this, I want to make random products that fall into the string, but every time I run the program I get the same product.

Where is the problem?

Here is the code in the generaProductos class:

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 I call the generaProductos() method basically:

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

When I execute my code, I always get the following:

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 with brown sizes S 16.99)

+5
source share
3 answers

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

change

 (int) Math.random() * 3 

to

 (int) (Math.random() * 3) 
+10
source
 num = (int) Math.random() * 3; 

there will always be 0 due to priority order.

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

+6
source

You can use the java math library to generate random integers. If you use Math.random() , you will get a random number only between 0.0 and 0.1

If you want to accept random integers between a wide range of integers, you can use the following function by providing two integer inputs, for example, Min and Max No.

 public static int RandInt(int max, int min){ return ((int) (Math.random()*(max - min))) + min; } 
0
source

Source: https://habr.com/ru/post/1239048/


All Articles