Freezy
Freezy

Reputation: 1

Picking random array element

I'm trying to grab a random value from this array. When I run the program it just prints 0 for x. Why isn't it printing the updated value that is returned from the function?

import java.util.*;
public class randomArray
{
    public static void main(String[] args)
    {
        int[] myArray = new int[]{1,2,3};
        int x = 0;
        getRandom(myArray, x);
        System.out.println(x);
    }
    public static int getRandom(int[] array, int h) 
    {
        int rnd = new Random().nextInt(array.length);
        return h;   
    }
}

Upvotes: 0

Views: 77

Answers (3)

Gilberto Aparicio
Gilberto Aparicio

Reputation: 11

Java passes the parameters by value, not by reference, so the x value is not updated inside the getRandom method. So when you call getRandom, the h variable is created and gets a copy of the value of the parameter x, that is the 0 value. Then you are returning the value of h that has a 0 value.

Upvotes: 1

Krystian G
Krystian G

Reputation: 2941

Java is "pass-by-value" for primitive types. That means when you pass a number as an argument to another method, the original value will not be modified inside that method. You expect that x variable becomes h variable, but these are two different variables and updating h will not update 'x'.

Upvotes: 0

Ivan
Ivan

Reputation: 8758

You need to change your getRandom() to the following

public static int getRandom(int[] array) 
{
    int rnd = new Random().nextInt(array.length); //generate random index
    return array[rnd]; // get element by random index
}

And then call System.out.println(getRandom(myArray));

Upvotes: 1

Related Questions