在Java中生成范围内的随机数

时间:2015-10-01 15:06:55

标签: java random floor

我无法弄清楚如何在一定范围内生成随机值,我不认为我现在在我的代码中所做的事情会产生最低值

public static void main(String[] args) {

    int rand1;
    int rand2;
    int rand3;
    double rand4;

    Random r = new Random();
    // Part A: Generate random integer number between 30 and 50 (inclusive) 
    rand1 = 30 + r.nextInt(50 - 30) + 1;
    // Part B: Generate random integer number between 20 and -20 (inclusive) 
    rand2 = -20 + r.nextInt(20 - (-20)) + 1;
    // Part C: Generate random integer number between -20 and -60 (inclusive) 
    rand3 = -60 + r.nextInt(-20 - (-60)) + 1;
    // Part D: Generate random integer number between 0.0 and 15.9999 (inclusive) 
    rand4 = 0.0 + (15.9999 - 0.0) * r.nextDouble();;

    /**
     * ****************************************************************************
     * Outputs Section *
     * ****************************************************************************
     */
    System.out.println("A random integer number between 30 and 50 (inclusive): " + rand1);
    System.out.println("A random integer number between 20 and -20 (inclusive): " + rand2);
    System.out.println("A random integer number between -20 and -60 (inclusive): " + rand3);
    System.out.println("A random integer number between 0.0 and 15.9999 (inclusive): " + rand4);

}

1 个答案:

答案 0 :(得分:0)

r.nextInt((50-30) + 1)代替r.nextInt(50-30) + 1