[英]Why is there an element that is not being displayed?
I am practicing creating a randomly generating integers in an array, then randomizing the elements in the array. 我正在练习在数组中创建随机生成的整数,然后将数组中的元素随机化。 All is well when I print the numbers, but there seems to be one element that does not print when I am displaying the randomized elements.
当我打印数字时一切都很好,但是当我显示随机元素时,似乎有一个元素不会打印。 Is there a step I am leaving out?
有没有我要走的步骤?
public class shufflingArrays {
public static void main(String[] args) {
int[] myList = new int[10];
System.out.println("Numbers:");
for(int i = 0; i < myList.length; i++) {
myList[i] = (int)(Math.random() * 100);
System.out.print(myList[i] + " ");
}
System.out.println("\nRandomized:");
for (int i = myList.length - 1; i > 0; i--){
//Generate index j randomly with 0 <= j <= i
int j = (int)(Math.random() * (i + 1));
//Swap myList[i]; with myList[j]
int temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
System.out.print(myList[i] + " ");
}
}
Your for
loop has condition i > 0
, which means when i == 0
it will terminate and not print out the first array element. for
循环的条件i > 0
,这意味着当i == 0
时它将终止并且不打印出第一个数组元素。
However, if you're doing the Fisher-Yates shuffle, as it appears, you do indeed need to go from myList.length-1
to 1, so your initial code was correct. 但是,如果您正在执行Fisher-Yates混洗,则确实需要将其从
myList.length-1
更改为1,因此您的初始代码是正确的。 You then can't print out all the elements in the array from the same loop, so either use another loop after to print out the elements, or add System.out.print(myList[0]);
然后,您将无法从同一循环中打印出数组中的所有元素,因此要么在打印出元素后使用另一个循环,要么添加
System.out.print(myList[0]);
after. 后。
Ex: for (int i = 4; i > 0; i--)
例如:
for (int i = 4; i > 0; i--)
will run the for
loop when i = 4, 3, 2, 1
only and not when i = 0
, because the condition there is i > 0
. 仅在
i = 4, 3, 2, 1
4、3、2、1时运行for
循环,而在i = 0
时不运行,因为条件i > 0
。 Change the i > 0
condition in for (int i = myList.length - 1; i > 0; i--)
to i >= 0
and you will get what you want. 将
for (int i = myList.length - 1; i > 0; i--)
的i > 0
条件更改为i >= 0
,您将得到想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.