这个用10个不同随机数填充数组的代码如何工作?

时间:2016-04-27 21:18:28

标签: java

有人可以解释一下这段代码背后的思考过程吗?我对它的运作方式感到困惑。这是代码正在解决的问题:

  

编写代码(使用一个或多个循环)以在1到10之间填充10个不同随机数的数组“a”。

非常感谢您的帮助!

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; 
        } 
    }
}

1 个答案:

答案 0 :(得分: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);