2016-04-27 44 views
-5

有人可以解釋這個代碼背後的思考過程嗎?我對它的工作原理感到困惑。這是該代碼是解決這樣的問題:這個代碼如何填充10個不同的隨機數字的數組?

寫代碼(使用一個或多個環)來填充的陣列的「a」與圖1和10

之間謝謝10張不同的隨機數這麼多的任何幫助!

public static void main(String[] args){ 
    //R8.8 
    int a[] = new int[10]; 
    Random randomGenerator = new Random(); 

    for (int i = 0; i < a.length; i++){ 
      a[i] = 1 + randomGenerator.nextInt(100); 
    } 

    for (int i = 0; i < a.length; i++) { 
      int number = 1 + randomGenerator.nextInt(100); 
      int count = 0; 
      for (int j = 0; j < i; j++) { 
      if (a[j] == number) { 
       count += 1; 
      } 
      } 
      if (count > 0) i -= 1; 
      else a[i] = number; 
     } 
    } 
} 
+4

[您是否嘗試過使用調試器進行調試?](https://en.wikipedia.org/wiki/Debugger) – robotlos

回答

0

見我的意見在代碼本身:

public static void main(String[] args){ 
    //make a new array of 10 integers 
    int a[] = new int[10]; 

    //declare an object which we can use to generate random numbers 
    //this object probably uses the system time to generate numbers that appear random 
    //but at the end of the day, java does it for us so 
    //we don't really need to know or care how it generates random numbers 
    Random randomGenerator = new Random(); 

    //loop over each element in our array 
    for (int i = 0; i < a.length; i++){ 
      //for each element, set that element to a random between 1 and 100 inclusive 
      //nextInt(x) gets a number between 0 (inclusive) and x (not inclusive) 
      //so to translate that to 1 to x inclusive, we need to add 1 to the result 
      a[i] = 1 + randomGenerator.nextInt(100); 
    } 

    //everything below here does literally nothing to solve the problem 
    //everything you need to fill the array with random numbers is above 

    for (int i = 0; i < a.length; i++) { 
      int number = 1 + randomGenerator.nextInt(100); 
      int count = 0; 
      for (int j = 0; j < i; j++) { 
      if (a[j] == number) { 
       count += 1; 
      } 
      } 
      if (count > 0) i -= 1; 
      else a[i] = number; 
     } 
    } 
} 

請注意,你應該使用1 + randomGenerator.nextInt(10);填補1和10,而不是1 + randomGenerator.nextInt(100);之間用數字數組。