Random类中的nextInt 和 Math.Random() 小练习

问题:求某个区间中的多少个数

例:求【10,23】之间10个整数

public class Four {
//     重写random中的nextint方法
    private static int random(int min,int max) {
        Random r1 = new Random();
        return r1.nextInt(max)%(max-min+1)+min;
    }

public static void main(String[] args) {
//    使用math.random完成[10,23)随机取10个数
    double[] sr = new double[10];
    for (int i = 0; i < sr.length; i++) {
        sr[i] = Math.round(Math.random()*13+10);
        System.out.println(sr[i]);
    }
System.out.println("-------------------------------");
//    使用Random类中的nextint方法
       double[] st = new double[10];
       for (int i = 0; i < 10; i++) {
//            st[i] = random(10, 23);
//    也可以直接这样写: 
           st[i] = new Random().nextInt(23)%(14)+10;
            System.out.println(st[i]);
      }
    }
}

根据API文档,Random类中的nextdouble方法和Math.Random是一样的含义,随机取的0.0到1.0之间的数,运用函数运算获得计算方式,从而取得所想要的,结果如下:

猜你喜欢

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