以下代码帮助理解随机数:
import java.util.Random;
public class Test3 {
public static void main(String[] args) {
Random random = new Random();
//随机产生一个int类型取值范围内的数字
int num1 = random.nextInt();
System.out.println(num1);
//产生0到100之间的随机数,不能产生101
int num2 = random.nextInt(101);
System.out.println(num2);
}
}
输出五个不重复的随机数:
import java.util.Random;
//随机输出五个不重复的数字(0到100之间)
public class Test3 {
public static void main(String[] args) {
Random random = new Random();
int[] array = new int[5];
for(int i = 0;i < array.length;i++){
array[i] = -1;
}
int index = 0;
while(index < array.length){
int num = random.nextInt(101);
if(contains(array,num)){
array[index++] = num;
}
}
for (int i = 0;i < array.length;i++){
System.out.println(array[i]);
}
}
public static boolean contains(int[] arrry,int key){
for(int i = 0;i < arrry.length;i++){
if(arrry[i] == key){
return false;
}
}
return true;
}
}