0

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;   
    }
}
6
  • You never modify x. And there's point in h. Commented Aug 31, 2018 at 23:11
  • 2
    What's the point of having second parameter in your getRandom() method? Commented Aug 31, 2018 at 23:12
  • @FarazDurrani this will not help as getRandom() returns its second argument not random value Commented Aug 31, 2018 at 23:13
  • @Ivan Trying to return rnd also gave me an error. Commented Aug 31, 2018 at 23:16
  • Assignment, perhaps? Commented Aug 31, 2018 at 23:16

3 Answers 3

1

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));

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That was a very fast response. So calling methods to a print statement just prints the thing that is returned to main?
Correct. Executing System.out.println(<some method>); will print value returned from that method.
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.