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

时间:2018-12-17 10:36:01

标签: java arrays loops random

我在将数组分配给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);

这也是我的输出:

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永远都不想动。如果我的代码很复杂或有任何错误,我们深感抱歉。编码愉快!

1 个答案:

答案 0 :(得分:5)

如果您要分配给x ,则应该执行以下操作:

x = xarray[0];

代替:

xarray[0] = x;
相关问题