简体   繁体   English

挑选随机数组元素

[英]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. 当我运行程序时,它只为x打印0。 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;   
    }
}

You need to change your getRandom() to the following 您需要将getRandom()更改为以下内容

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)); 然后调用System.out.println(getRandom(myArray));

Java passes the parameters by value, not by reference, so the x value is not updated inside the getRandom method. Java通过值而不是通过引用传递参数,因此x值不会在getRandom方法内更新。 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. 因此,当您调用getRandom时,将创建h变量,并获取参数x值(即0值)的副本。 Then you are returning the value of h that has a 0 value. 然后,您将返回值为0的h值。

Java is "pass-by-value" for primitive types. Java是原始类型的“按值传递”。 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'. 您期望x变量变为h变量,但这是两个不同的变量,更新h不会更新'x'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM