6

我无法将随机数放入我的测试类的数组中。代码在java中。我不能单独完成,因为最终我必须用多达 600 个值填充数组。这是测试类:

import java.util.Random;

public class test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        int size = 1000;
        int max = 5000; 
        int[] array = new int[size];
        int loop = 0; 

        Random generator = new Random();
        //Write a loop that generates 1000 integers and 
        //store them in the array using generator.nextInt(max)

        generator.nextInt(max); //generating one

        //I need to generate 1000
        //So I need some kind of loop that will generate 1000 numbers. 
        for (int i =0; i<1000; i++)
        {
            generator.nextInt(max);
        }

        /**
         * After I do this, I'll have the array, array. 
         * Then comes what's under this. 
         * THat method is for measuring the time.
         * System.currentTimeMillis();, 
         * with this, I can collect a time for the start of the method
         * and one for the end. 
         * Time at the end, minus the time at the start
         * gets us the running time. 
         */

        long result;

        long startTime = System.currentTimeMillis();
        sort.quickSort(array,  100,  array.length-1);

        long endTime = System.currentTimeMillis();
        result = endTime-startTime; 

        System.out.println("The quick sort runtime is " + result + " miliseconds");

        long result2;

        long startTime2 = System.currentTimeMillis(); 
        sort.partition(array, 100, array.length-1); 
        long endTime2 = System.currentTimeMillis();
        result2 =  endTime2 - startTime2;
        System.out.println("The partition runtime is "+result2 + " miliseconds");

        long result3;

        long startTime3 = System.currentTimeMillis();
        sort.bubbleSort(array, 100);
        long endTime3 = System.currentTimeMillis();
        result3 = endTime3-startTime3;
        System.out.println("The bubble sort runtime is "+result3 + " miliseconds");

        long result4;

        long startTime4 = System.currentTimeMillis();
        sort.selectionSort(array, 100); //change the second number to change
        //the size of an array. 
        long endTime4 = System.currentTimeMillis();
        result4 = endTime4-startTime4;
        System.out.println("The selection sort runtime is "+result4 + " miliseconds");

    }
}

我已经完成了测试类和它调用函数的另一个类,并且没有错误。我只需要以某种方式将随机值放入数组中。任何建议将不胜感激。

如果你看一下代码,你会发现我已经做了一个小函数来自己生成数字。我只是不知道该怎么做才能使数字进入数组。

4

2 回答 2

8

您只需要更改循环内的行以将随机数分配给数组的当前索引。

array[i] = generator.nextInt(max);

查看Arrays教程线程,了解有关创建、初始化和访问数组的所有信息。

顺便说一句,1000您的循环条件可能应该上升到,而不是重复size

for (int i = 0; i < size; i++)
于 2013-04-25T03:03:31.733 回答
1

从 1.8 开始

Arrays.setAll(array, i -> {
    return generator.nextInt(max);
});

这会用 0(含)和(不含)之间的随机数填充您的数组max

进一步阅读:数组类IntUnaryOperator 接口

话虽如此,我更喜欢使用 Bill the Lizard 提供的方法,使用循环来初始化每个值。

于 2016-06-16T20:50:24.800 回答