取某个区间的不同的随机数

/*1。创建数组
 * 2.for循环
 * 3.判断数组内的数是否和随机数相同,如果相同则重新获取随机数
 * 获取10个1-20之间的随机数,要求不能重复
 * */
public class Random {
     public static void main(String[] args) {
        boolean b1 = true;
        double[] dd =  new double[10];
        dd[0] = Math.round((Math.random()*19+1));
        for (int j = 1; j < dd.length; j++) {
            int i = j-1;
            double s = Math.round((Math.random()*19+1));
            while (b1==false && i>=0) {
                s = Math.round((Math.random()*19+1));
                if (dd[i]==s) {
                    b1 = false;
                } else {
                    i--;
                }
            }
            dd[j]=s;
        }
        for (int i = 0; i < dd.length; i++) {
            System.out.println(dd[i]);
        }
    }
}

代码还是过于复杂,嵌套过多

猜你喜欢

转载自www.cnblogs.com/lkkkk/p/12198435.html