How to make an array from a method not change each time the method is called

Helpmewithjava :

I made a method that uses the random class to generate a number. These numbers are used to fill in an array. This method returns the filled in array. So, I have a few other arrays that I made which are equal to the returned array. However, these arrays are all the same even though they should be random.

I tried printing how each array that calls the random, right under where it calls. This gave me different arrays. But if I move my prints to under all the calls then the arrays are all the same. Also I think this is an array issue because I only have this problem with arrays.

    public static int[] numberGenerator(int[] array) {
        Random rand = new Random();
        int min = 0;
        int max = 0;
        int x = 0;

        for (int j = 0; j < array.length; j++) {        

            if (j == 0) {
                min = 1;
                max = 15;
            }
            if (j == 1) {
                min = 16;
                max = 30;
            }
            if (j == 2) {
                min = 31;
                max = 45;
            }
            x = rand.nextInt((max - min) + 1) + min;
            array[j] = x;                               
        }
        return array;
    }

    public static void main(String[] args) {
        int[] array = {' ', ' ', ' '};
        int[] array1 = numberGenerator(array);  
        int[] array2 = numberGenerator(array);

        System.out.println(array1[1]);
        System.out.println(array2[1]);          
    }
}

Distinct arrays are what I'm looking for.

Jon Skeet :

You're modifying the array that you pass into the method. Given that you don't use the existing content of the array anyway, it would be better to just pass in the length that you want, and create a new array in the method:

public static int[] numberGenerator(int length) {
    int[] array = new int[length];
    // Rest of method as before
}

Then change your main method to:

public static void main(String[] args) {
    int[] array1 = numberGenerator(3);  
    int[] array2 = numberGenerator(3);

    System.out.println(array1[1]);
    System.out.println(array2[1]);          
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112744&siteId=1