어떤 이유로 든 내가 만든 for 루프 외부에서 배열 값에 액세스 할 수 없습니다. 배열을 로컬로 선언했습니다. 하지만 사용자가 값을 입력해야 할 때 어떤 이유에서든 바인딩 된 값은 계속 0
을 제공합니다. for 루프 내부의 배열로부터 정보를 얻는 방법이 "일반화"되어 다른 함수에서도 사용할 수 있습니다. 당신은 당신은 배열의 각 요소를 초기화하지 않는 for-loop
을 강화 사용하고 있기 때문에입니다작동 할 때에도 배열 값에 액세스 할 수 없습니다.
import java.util.*;
public class Array {
public static void main(String[] args) throws IndexOutOfBoundsException {
int[] array = new int[100];
try{
for(int i: array){
array[i] = (int)(Math.random()*100);
System.out.println(array[i]);
}
Scanner input = new Scanner(System.in);
System.out.println("Please enter an index for which you would like to see: ");
int index = input.nextInt();
System.out.println(array[index]);
}catch(IndexOutOfBoundsException ex){
System.out.println("Please enter in an index thta is not out of bounds");
}finally{System.out.println("--------------------------");}
}
}
그럼 머리에 얼굴을 손바닥 이잖아. 그러나 논리 현명한 shouldnt "강화"에 대한 일반적인 기능을 가지고 루프에 대한 일반, 그리고 몇 가지? – Dcdw51
@ Dcdw51 내 대답에 설명을 추가했습니다. 체크 아웃하십시오. 향상된 for 루프는 단지 반복을위한 것이지 인덱스 값이 할당 변수 배열에 대해 증가하지 않기 때문에 일반적인 배열 할당을위한 것이 아닙니다 –