[英]Why is there an element that is not being displayed?
我正在練習在數組中創建隨機生成的整數,然后將數組中的元素隨機化。 當我打印數字時一切都很好,但是當我顯示隨機元素時,似乎有一個元素不會打印。 有沒有我要走的步驟?
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] + " ");
}
}
for
循環的條件i > 0
,這意味着當i == 0
時它將終止並且不打印出第一個數組元素。
但是,如果您正在執行Fisher-Yates混洗,則確實需要將其從myList.length-1
更改為1,因此您的初始代碼是正確的。 然后,您將無法從同一循環中打印出數組中的所有元素,因此要么在打印出元素后使用另一個循環,要么添加System.out.print(myList[0]);
后。
例如: for (int i = 4; i > 0; i--)
僅在i = 4, 3, 2, 1
4、3、2、1時運行for
循環,而在i = 0
時不運行,因為條件i > 0
。 將for (int i = myList.length - 1; i > 0; i--)
的i > 0
條件更改為i >= 0
,您將得到想要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.