每次都获得相同的随机数

时间:2013-03-02 22:18:01

标签: java random

我正在尝试编写一个程序,为每位教师生成随机位置和随机小时数的随机学校时间表,但每天都有固定的总时间。目前该程序已编写为工作两天,我遇到了一个问题:两天之间的随机生成值是相同的:

import java.util.Random;
public class randomTimetable {  

    public static void main(String[] args) {    
        String newLine = System.getProperty("line.separator"); 
        System.out.println("For each day (x + y + ... n) >= 5 and" +newLine +"(x && y && ... n) <= 2" +newLine);
        createTimetable();

    }
private static void createTimetable() { 
    String x_g1 = "x";
    String y_g1 = "y";
    String z_g1 = "z";
    String m_g1 = "m";
    String[] arrayTimetablePosition1={x_g1, y_g1, z_g1, m_g1};
    String newLine = System.getProperty("line.separator"); 


    System.out.println("Work In Progress" +newLine +"Total subjects = 5" +newLine +"Day 1");    

    Random rand = new Random();
    int min = 0;
    int max = 2;
    int x1 = rand.nextInt(max - min + 1) + min;
    int y1 = rand.nextInt(max - min + 1) + min;
    int z1 = rand.nextInt(max - min + 1) + min;
    int m1 = rand.nextInt(max - min + 1) + min;
    while((x1 + y1 + z1 + m1) != 5) {
        x1 = rand.nextInt(max - min + 1) + min;
        y1 = rand.nextInt(max - min + 1) + min;
        z1 = rand.nextInt(max - min + 1) + min;
        m1 = rand.nextInt(max - min + 1) + min;
    }   

    System.out.println("x1 = " +x1 +newLine +"y1 = " +y1 +newLine +"z1 = " +z1 +newLine +"m1 = " +m1 +newLine);
    System.out.println("Total subjects = 5" +newLine +"Day 2");
    int x2 = rand.nextInt(max - min + 1) + min;
    int y2 = rand.nextInt(max - min + 1) + min;
    int z2 = rand.nextInt(max - min + 1) + min;
    int m2 = rand.nextInt(max - min + 1) + min;

    while((x2 + y2 + z2 + m2) != 5 && (x1 == x2 || y1 == y2 || z1 == z2 || m1 == m2)) {
        x2 = rand.nextInt(max - min + 1) + min;
        y2 = rand.nextInt(max - min + 1) + min;
        z2 = rand.nextInt(max - min + 1) + min;
        m2 = rand.nextInt(max - min + 1) + min;
        }   
    System.out.println("x2 = " +x1 +newLine +"y2 = " +y1 +newLine +"z2 = " +z1 +newLine +"m2 = " +m1 +newLine);
    }
}

具体地说,x1的值与x2相同,y1中的一个与y2相同,依此类推。

4 个答案:

答案 0 :(得分:3)

你是随机构造没问题 - 你正在使用默认构造函数,它会自动将时间用作种子:

public Random() { this(System.currentTimeMillis()); }

但是在上一次调试打印语句中有一个复制/粘贴错误。你的标签是x2,但是你要打印x1等等。

System.out.println("x2 = " +x1 +newLine +"y2 = " +y1 +newLine +"z2 = " +z1 +newLine +"m2 = " +m1 +newLine);

答案 1 :(得分:1)

看起来你正在使用相同的种子。见:

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

答案 2 :(得分:1)

我看不到伪随机数生成器的任何初始化。

您需要设置PRNG的种子。

答案 3 :(得分:0)

LOL,这是一个复制粘贴错误

最后一行应该阅读

System.out.println(“x2 =”+ x2 + newLine +“y2 =”+ y2 + newLine +“z2 =”+ z2 + newLine +“m2 =” + m2 + newLine);

但这听起来像是一个经典的随机种子问题。这很有趣。