Home >Java >javaTutorial >How to generate random numbers in Java
1. Use Math.random() (generating a double between 0-1) method in j2se:
such as
public void numCreate(){ int array[] = new int[10]; for(int i=0;i<10;i++){ array[i]=(int)(Math.random()*100); for(int j=0;j<i;j++){ if(array[i] == array[j]){ i--; break; } } } for(int t=0;t<array.length;t++){ System.out.println(array[t]); } }
2. Use the Random object to generate random numbers, he Can generate random integers and floating point numbers. Use the next..() method of the Random instance. In general, choose the method without seeds to generate random numbers. Such as
public void numCreate(){ int array[] = new int[10]; for(int i=0;i<10;i++){ Random r = new Random(); array[i] = r.nextInt(100); for(int j=0;j<i;j++){ if(array[i] == array[j]){ i--; break; } } } for(int t=0;t<array.length;t++){ System.out.println(array[t]); } }
The parameters in the nextInt method can set the range of generated numbers. Between 0 (inclusive) and the specified value (exclusive).
The above is the detailed content of How to generate random numbers in Java. For more information, please follow other related articles on the PHP Chinese website!