使用随机数填充数组但有限制

时间:2015-05-16 17:01:22

标签: java arrays random

我正在尝试将随机值添加到数组中。用户必须说明有多少值(长度)并给出minval和maxval(e.x.minval = 3表示3以下没有值)。 这就是我所拥有的:

int[] GetallenArray;

public IntegerArray(int length, int maxval, int minval) {

    this.GetallenArray = new int[length];
    for (int i = 0; i < GetallenArray.length; i++)
    {
        this.GetallenArray[i] = // Random values between the maxval and minval
    }
}

2 个答案:

答案 0 :(得分:2)

在for循环

之外实例化Random个对象
Random random = new Random();

然后在for循环中

this.GetallenArray[i] = random.nextInt((maxval - minval)+1) + minval;

答案 1 :(得分:1)

Random random = new Random();
this.GetallenArray = new int[length];
  for (int i = 0; i < GetallenArray.length; i++){
    this.GetallenArray[i] = random.nextInt(50) + 1; 
   //50 is the maximum and the 1 is our minimum 
  }
}