作业帮 > 综合 > 作业

java:用Random产生随机数放在数组中,就像36选7那样.7个数字都不相同!

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/23 18:04:09
java:用Random产生随机数放在数组中,就像36选7那样.7个数字都不相同!
我主要想知道,Random产生的随机数有可能相同.第一次可能是2,第二次也可能是2.如果第二次也是2的话就重新产生.好像是关于数组地址判断的,我也不清楚.
import java.util.Random;
public class Rand {
\x05public static void main(String[] args) {
\x05\x05final int[] nums = new int[7];
\x05\x05
\x05\x05Random rand = new Random();
\x05\x05
\x05\x05for(int i = 0; i < nums.length; i++){
\x05\x05\x05int randNum = rand.nextInt(35);//simple test,the number not grater than 35
\x05\x05\x05
\x05\x05\x05boolean isExistingNum = false;
\x05\x05\x05//check whether it's already in the array;
\x05\x05\x05for(int j =0; j < i; j++){
\x05\x05\x05\x05if(nums[j] == randNum){
\x05\x05\x05\x05\x05isExistingNum = true;
\x05\x05\x05\x05\x05break;
\x05\x05\x05\x05}
\x05\x05\x05}
\x05\x05\x05
\x05\x05\x05if(isExistingNum){
\x05\x05\x05\x05i--;
\x05\x05\x05}else{
\x05\x05\x05\x05nums[i] = randNum;
\x05\x05\x05}
\x05\x05}
\x05\x05
\x05\x05//print the array
\x05\x05for(int i = 0; i < nums.length; i++){
\x05\x05\x05System.out.println(nums[i]);
\x05\x05}
\x05}
}