【问题标题】:Resizing an Integer Array with Random Numbers使用随机数调整整数数组的大小
【发布时间】:2015-04-24 17:32:11
【问题描述】:

我正在尝试创建一个 Integer[],每个循环都会增加 10 的倍数。一旦设置了 Integer[] 大小,我希望它用随机整数填充数组。我能够使数组的大小增加,但其中存储的值是空的。 对我来说,这意味着数组正在正确调整大小,但它们的元素没有被分配给任何东西。我正在尝试一个双 for 循环,内部循环分配随机值。如果有更好的方法来做到这一点(我确定我的 b/c 没有运行!)你能帮忙吗?

这是我创建的 Int[]

 public class TimeComplexity {

    Integer[] data;

    public TimeComplexity() 
    {
        Random random = new Random();

        for (int N = 1000; N <= 1000000;  N *= 10) 
        {
            N = random.nextInt(N);
            data = new Integer[N];
            //checking to see if the random numbers were added.
            //array size is okay but locations aren't taking a 
            //random number
            System.out.println(Arrays.toString(data));

        }

    }

如果您对我的主要课程的输出感兴趣。 (这不是问题的一部分,但如果你有建议我会喜欢的!)

public class TimeComplexityApp {

    private static int MAXSIZE = 1000000;
    private static int STARTSIZE = 1000;

    public TimeComplexityApp() 
    {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {

        TimeComplexity time = new TimeComplexity();
        System.out.println(time);
        System.out.printf("%-6s %13s %13s\n\n\n","ARRAY","int","INTEGER");

        for (int N = STARTSIZE; N <= MAXSIZE;  N *= 10) 
        {
            double d = 1.0;
            System.out.printf("\n%-6d %15.2f %15.2f\n", N, d, d);
        }
    }

}

【问题讨论】:

  • 那里实际上没有双 for 循环。您需要一个内部循环,将随机数分配给每个索引。您在复制代码时是否遗漏了它,或者这是您当前的代码?
  • 这是我当前的代码
  • 然后你需要另一个循环来遍历并设置值。您已经延长了长度,但您从未将它们分配给任何东西。看起来 @ControlAltDel 的代码 sn-p 是一个很好的 for 示例,您可以将其放入现有的 for 循环中。

标签: java arrays for-loop random


【解决方案1】:

在第一个显示缺少初始化整数数组元素的源代码中。

数据 = 新整数 [N];只创建大小为 N 的整数数组,缺少包含数组每个单元格中的元素。

所以,只需要一个循环来完成每个元素或元胞数组:

for (int i = 0; i <N; i ++)
    data [i] = random.nextInt (N);

现在这个数组是完整的,不会对每一项都返回 NULL。

【讨论】:

    【解决方案2】:

    在循环的每次迭代中,您都在创建一个随机(int 大小)长度的新数组。但你从来没有把任何东西放进去。正确的做法是:

    int[] vals = ...;
    for (int i = 0; i < end - start; i++) {
      if (vals.length < i; i++) {
         //1. create new larger int[]
         //2. copy the old array into the new array
         //3. vals = yourNewArray
      }
      vals[i] = random.nextInt();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-10
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      相关资源
      最近更新 更多