Java:创建一个int数组,然后创建每个int大小的新数组

时间:2018-03-25 23:40:52

标签: java arrays for-loop selection-sort

编辑:教授帮我解决了问题(见下文)

public class TestSortMethods {

public static void main(String[] args) {

    int[] array0 = new int[] {10, 50, 100, 250, 500, 750, 1000};

    for (int i = 0; i < array0.length; i++) {
        int[] array1 = SortMethods.randomIntArray(array0[i], 100.0);
        int[] array2 = SortMethods.copyArray(array1);
        SortMethods.printArray(array1);
        System.out.println("\nSorting array\n");
        SortMethods.selectionSort(array1);
        int c = SortMethods.selectionSortComparisons(array2);
        System.out.println(c);
        }
    }
    }

我没有别的方式来表达这一点,但是要啰嗦,所以我提前道歉。对于编程任务(家庭作业),我们正在测试比较以选择不同大小的随机数阵列。我无法弄清楚如何编写代码,以便“array1”,一个随机数组10-100包含将使用array0的第一个索引的长度创建。我不确定如何构造一个for循环来做到这一点。基本上会有一个包含10个随机数的数组,然后是50,100,250等。我的代码不完整

public class TestSortMethods {

    public static void main(String[] args) {

        //When completing the last step of the assignment, it's much faster to create an array containing the 
        //different sizes you want to sort (new int[] {10, 50, 100, ...}) and use a for loop to generate, copy,
        //and sort random arrays of those sizes. If you aren't sure how to do this, I'd recommend asking for help. 
        //This involves some basic skills with arrays and loops that are useful to have at this point in the class.

        // make array with different sizes (in excel file) for loop making array which tells 
        //all the different sizes it would be sorting.

        int[] array0; 
        array0 = new int[]{10, 50, 100, 250, 500, 750, 1000};
        int[] array1 = SortMethods.randomIntArray(10, 100.0);

        for (int i = 0; i < (array0.length); i++) {
            array1[i] += 1;
        }
        int[] array2 = SortMethods.copyArray(array1);
        SortMethods.printArray(array1);
        System.out.println("\nSorting array\n");
        SortMethods.selectionSort(array1);
        int c = SortMethods.selectionSortComparisons(array2);
        System.out.println(c);
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个快速的方法,可以完成您在问题中所说的内容:

public static void main(String[] args) {
    int[] arraySizes = new int[]{1,2,3,4};
    int[] arrayOutput;
    Random random = new Random();
    int maximumRand = 100;
    int minimumRand = 10;

    //for every value in arraySizes array
    for (int i: arraySizes){
        //initialize  arrayOutput to the size in this entry of arraySizes
        arrayOutput = new int[i];
        //fill the output array with random numbers based on value of arraySizes entry
        for(int j = 0; j <i; j++){
            arrayOutput[j] = random.nextInt((maximumRand - minimumRand) + 1);
        }
        System.out.println(Arrays.toString(arrayOutput));
    }
}

您可以在以下IDEONE链接上看到执行的代码 https://ideone.com/ruLsNu

此输出:

[33]
[81, 83]
[79, 84, 82]
[70, 89, 9, 72]

arraySizes数组中列出的长度为1,2,3和4的随机整数数组的代码输出。