배열에서 무작위로 생성 정수를 생성 한 다음 배열의 요소를 무작위로 추출하는 연습을하고 있습니다. 숫자를 인쇄하면 모두 잘되지만 무작위 요소를 표시 할 때 인쇄되지 않는 요소가있는 것 같습니다. 나가는 단계가 있습니까?표시되지 않는 요소가있는 이유는 무엇입니까?
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] + " ");
}
}
감사합니다. 그런 작은 일 때문에 나는 그 실수가 어디서 무엇인지를 깨닫지 못했습니다. 나는 그것을 'i> -1'로 바꾸었고 나는 원했던 것처럼 인쇄했습니다. 왜 이런거야? –
'i> -1'로'i == 0'을 실행하면, 그 요소도 출력 할 수 있습니다. – Iluvatar