Generate non-repeating random numbers java
java can use the method in the Math class to generate random numbers. If it is not random, you can use List for judgment storage. (Recommended tutorial: java tutorial )
1. Call the random() method in the Math class below java.lang to generate random numbers
Create a new file with the suffix name java, and the file name is MyRandom. Write the following code in this class:
public class MyRandom { public static void main(String[] args) { int radom = (int)(Math.random()*10); System.out.println(radom); } }
Math.random() //Produces 0~1 a random decimal between.
To generate an integer between 0 and 9 is: (int)(Math.random()*10);
To generate an integer between 1 and 10 you can write: (int)(Math.random()*10 1);
And so on: to generate a number between 0 and n, it should be written as: Math.random()*n;
For example: Generate an int type array with a length of 50, and insert numbers between 0-50 into it randomly, and they cannot be repeated.
2. Use the contains method of List to make repeated judgments
public class MyRandom { public static void main(String[] args) { int[] intRandom = new int[50]; List mylist = new ArrayList(); //生成数据集,用来保存随即生成数,并用于判断 Random rd = new Random(); while(mylist.size() < 50) { int num = rd.nextInt(51); if(!mylist.contains(num)) { mylist.add(num); //往集合里面添加数据。 } } for(int i = 0;i <mylist.size();i++) { intRandom[i] = (Integer)(mylist.get(i)); } } }
The above is the detailed content of Generate unique random numbers java. For more information, please follow other related articles on the PHP Chinese website!