如何将数组中的随机数分配给值?

Ene*_*kan -3 java arrays random loops

我有一个数组的问题,并将它们分配给像float这样的值.这是我的代码

System.out.print("Please enter the number of iteration: ");
    Scanner scn = new Scanner(System.in);
    int inumber = scn.nextInt(); // i get the iteration number

        Random rnd = new Random();
        float x = -10 + rnd.nextFloat() * 20; // i created random number between 10 and -10
        System.out.println("My x = " +x);

            float[] xarray = new float[4]; // created my test array
            Random arrayrnd = new Random();


        for (int i=0;i<inumber;i++) { // created a for loop with that number

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

                xarray[j] = arrayrnd.nextFloat(); // also created random for array and assigned them
            }

            Arrays.sort(xarray); // i sorted the array
            xarray[0] = x; // i tried to assign the smallest number to x but didn't work

            System.out.println("t="+i+" My new x = " +x);
Run Code Online (Sandbox Code Playgroud)

这是我的输出:

Please enter the number of iteration: 2 My x = -6.2841988 t=0 My new x = -6.2841988 t=1 My new x = -6.2841988

我只是不明白为什么我的x没有改变,即使我试图给x赋值新值.我想让我的x在循环的每个回合中改变并获得最小数量的数组.但似乎x永远不想移动.如果我的代码很复杂或者我有任何错误,我很抱歉.快乐的编码!

小智 5

如果要分配TO x,您应该:

x = xarray[0];
Run Code Online (Sandbox Code Playgroud)

代替:

xarray[0] = x;
Run Code Online (Sandbox Code Playgroud)