【问题标题】:How can I assign the random number from array to value? [closed]如何将数组中的随机数分配给值? [关闭]
【发布时间】:2019-05-17 17:05:02
【问题描述】:

我对数组和将它们分配给浮点等值有疑问。这是我的代码

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

【问题讨论】:

  • 如果你想改变它,你应该把float x = -10 + rnd.nextFloat() * 20;移动到你的循环中
  • 你一直在使用同一个 x,而不是新值
  • xarray[0] = x; // i tried to assign the smallest number to x but didn't work .----您不是将最小的分配给 x,而是将签证分配给虎钳

标签: java arrays loops random


【解决方案1】:

如果你想分配给 x,你应该这样做:

x = xarray[0];

代替:

xarray[0] = x;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-01
    • 2017-02-14
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多