[英]How does this code that fills an array with 10 distinct random numbers work?
Can someone please explain the thought process behind this code?有人可以解释一下这段代码背后的思考过程吗? I am kind of confused on how it works.我对它的工作方式有点困惑。 This is the question that the code is addressing:这是代码要解决的问题:
Write code (using one or more loops) to fill an array "a" with 10 different random numbers between 1 and 10.编写代码(使用一个或多个循环)用 1 到 10 之间的 10 个不同随机数填充数组“a”。
Thank you so much for any help!非常感谢您的帮助!
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;
}
}
}
See my comments in the code itself:在代码本身中查看我的评论:
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;
}
}
}
Please note that you should use 1 + randomGenerator.nextInt(10);
请注意,您应该使用1 + randomGenerator.nextInt(10);
to fill the array with numbers between 1 and 10, not 1 + randomGenerator.nextInt(100);
用 1 到 10 之间的数字填充数组,而不是1 + randomGenerator.nextInt(100);
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.