【问题标题】:I need to know how to fill an arrays indexes with other arrays我需要知道如何用其他数组填充数组索引
【发布时间】:2012-03-18 13:33:01
【问题描述】:

我想创建一个包含 5 个索引的数组,每个索引都有一个索引,每个索引都有另一个完整的数组。 5 索引内的每个数组都需要如下索引(10、100、1000、10000),但我不知道如何在我的 for 循环中填充这样的数组,通常与数组一起使用,没有它运行到无穷大,因为我在哪里 for(int x = 0; x

如果这有助于更好地理解,所有这些代码也是它自己类的方法的一部分。

public int ArrayArray(int arraySize, int randomNumber) {

    arraySizes = arraySize;

    for(int x = 0; x < array.length; x++) {
        size = 0;

    Random gen = new Random(randomNumber);  

    int[]ten;
    ten = new int[arraySize];
    int[] hundred;
    hundred = new int[arraySize];
    int[]thousand;
    thousand = new int[arraySize];
    int[]tenThousand;
    tenThousand = new int[arraySize];

    int[] array = {ten[x] = gen.nextInt(10), hundred[x] = gen.nextInt(100), 
            thousand[x] = gen.nextInt(1000), tenThousand[x] = gen.nextInt(10000)};

     return array[];
    }

这稍微改变了我的问题,我认为我在处理后得到了它。这看起来会返回我想要它做的事情吗?我将有一个驱动程序,我将使用给定的数组大小和给定数量的随机整数调用此方法。

【问题讨论】:

  • 您可以编辑您的帖子并输入您遇到问题的代码吗?
  • 是的。发布您的代码,我在处理您的问题时遇到了困难。
  • 这个方法的返回也不起作用
  • 退货是您目前唯一遇到的问题吗?
  • 是的,我不确定我应该返回什么

标签: java arrays methods for-loop


【解决方案1】:

如果您尝试返回并排列您的函数,请尝试以下操作:

public int[][] ArrayArray(int arraySize, int randomNumber) {
    Random gen = new Random(randomNumber);
     int[]ten= new int[10];
     int[] hundred= new int[100];
     int[]thousand= new int[1000];
     int[]tenThousand= new int[10000];     
     int[][] array = {ten,hundred,thousand,tenthousand};
    return array;
}

注意它是int[][] 而不是int[]。这是因为您尝试返回的数组是二维数组,而不仅仅是一维数组。

让我知道这是如何工作的。

【讨论】:

  • 我去掉了 arraySize 参数,因为我可以在方法中说出给定数组的大小,即。整数[]十;十 = 新的 int[10];我还需要创建多数组吗?
  • 是的,否则你会得到一堆相同大小的数组。但是你想用这些数组做什么?你想用随机数填充它们吗?
  • 我现在在课堂上做排序方法,我的任务是获取这些特定的数组,并使用排序方法以五种不同的方式排列它们(降序、升序和 3 个随机生成的列表) .我不确定我的做法是否正确。
  • "在这部分,您将比较排序算法在不同列表上的性能。您应该输出每种排序算法对每个列表进行的比较次数。生成以下 5 个 4 种大小的列表( 10、100、1,000 和 10,000 个元素):1. 递增顺序 (1, 2, 3, ...) 2. 倒序 (10,000/1000/100/10 . . . .1) 3. 三个随机生成的列表(确保它们不同!)”
  • 这就是你的作业给你的所有指示吗?他们会给你一个排序算法吗?
【解决方案2】:

如果您尝试创建数组数组,那么多维数组是可行的方法。

int arraySize = 10;

int[]ten = new int[arraySize];
int[] hundred = new int[arraySize];
int[]thousand = new int[arraySize];
int[]tenThousand = new int[arraySize];

int[][] array = new int[4][arraySize];

array[0] = ten;
array[1] = hundred;
array[2] = thousand;
array[3] = tenThousand;

传递二维数组也与数组相同。例如。

public static int hello(int[][] pass) {
    return pass;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多