2013-04-25 107 views
4

我在將測試類中的數組放入數組時遇到了麻煩。代碼是用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"); 

    } 
} 

我已經通過測試類,它從調用函數其他類已經走了,沒有錯誤。我只需要以某種方式將隨機值放入數組中。任何意見將不勝感激。

如果你看看代碼,你可以看到我已經做了一個小函數來自己生成數字。我只是不知道該怎麼做才能讓數字進入數組。

回答

8

您只需要更改循環內部的行以將隨機數分配給數組的當前索引。

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

退房的Arrays教程線程,你需要了解創建,初始化和訪問數組的一切。

順便說一句,代替重複1000,您的循環條件可能應該高達size

for (int i = 0; i < size; i++) 
+0

這似乎已經成功了。謝謝。 – 2013-04-25 03:18:59

+3

@MariaStewart你明白爲什麼這是必要的嗎?問問你自己:如果你沒有把它們放在那裏,你生成的值會如何進入數組?如果你採用代碼,插入代碼並認爲它​​「神奇地工作」,那對你來說並不是很有益。 – rliu 2013-04-25 03:26:57

0

由於1.8

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

這充滿你的隨機數介於0(含)max(獨家)陣列。

延伸閱讀:The Arrays ClassThe IntUnaryOperator Interface

話雖這麼說,做,我寧願使用由比爾蜥蜴提供的方法,使用循環來初始化每個值。