Brian Murphy
Brian Murphy

Reputation: 11

static arrays are not the same [java]

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....

Upvotes: 1

Views: 93

Answers (3)

muneebShabbir
muneebShabbir

Reputation: 2538

Pass Seed in constructor of Random it will generate the same number every time

Upvotes: 1

Makoto
Makoto

Reputation: 106470

Pass a seed on initialization with Random(long seed). This will guarantee that the sequence of numbers generated is always the same (since it's a pseudo-random number generator).

Upvotes: 1

MrSmith42
MrSmith42

Reputation: 10151

Use the Random constructor with seed

public static Random randomNumbers = new Random(42);

This way always the same sequence of random numbers is generated. 42 is only an example, you can use any value you want.

Upvotes: 2

Related Questions