1

I'm trying to create a Java program that generates an amount of seats taken in an airplane. So far, I have been able to do this, but my problem is every time I run the client the numbers generated are different. I need them to be the same every time...

I'm not sure what I'm doing wrong, can anybody help me?

import java.util.Random;
import java.util.Arrays;

public class Airplane {
    public static Random randomNumbers = new Random();
    public static int[] oSeatLeft = new int[10];
    public static int[] mSeatLeft = new int[10];
    public static int[] wSeatLeft = new int[10];
    public static int oSeat = 0;
    public static int mSeat = 0;
    public static int wSeat = 0;
    public static final int sCheck = 0;

    public void genWSeats() {

        int randSeatFill = 0;
        if (wSeat == 0) {
            for (int counter = 0; counter < wSeatLeft.length; counter++) {
                randSeatFill = randomNumbers.nextInt(2);
                if (randSeatFill == 1) {
                    wSeatLeft[counter] = 1;
                }
            }
            if (wSeat == 0) {
                wSeat++;
            }
        }
    }

    public int[] getWSeats() {
        System.out.println(java.util.Arrays.toString(wSeatLeft));
        return wSeatLeft;
    }
}

The purpose of static int wSeat is supposed to be a checker. If wSeat is greater than zero, then it should not randomly generate numbers for the array. Not sure exactly what is going wrong here....

4

3 回答 3

2

使用Random带有种子的构造函数

public static Random randomNumbers = new Random(42);

这种方式总是生成相同的随机数序列。42 只是一个例子,你可以使用任何你想要的值。

于 2013-04-24T04:54:59.750 回答
1

使用 .在初始化时传递种子Random(long seed)。这将保证生成的数字序列始终相同(因为它是一个伪随机数生成器)。

于 2013-04-24T04:55:22.830 回答
1

在它的构造函数中传递种子Random每次都会生成相同的数字

于 2013-04-24T04:57:36.613 回答