2016-12-16 1 views
-3

내 코드를 사용하는 동안 I가, 단말 인쇄를 컴파일 할 때ArrayIndexOutOfBoundsException가 이차원 배열

Scanner sc = new Scanner(System.in); 
int v=sc.nextInt(); 
int s=sc.nextInt(); 
int[][] n = new int [v][s]; 
for (int i=0; i<n.length; i++) { 
    for (int j=0; j<n[v].length-1; j++) { 
     n[i][j]=sc.nextInt(); 
    } 
} 
System.out.print(n[v][s]); 
System.out.println(); 

이다

java.lang.ArrayIndexOutOfBoundsException : Plevel에서 4
. main (Plevel.java:13)

누군가 내가 뭘 잘못하고 있는지 말해 줄 수 있습니까?

+1

이 새로운 int [v] [s]와이 n [v] .length는 함께 사용할 수 없습니다. 배열의 크기 번호는 유효한 인덱스 자체가 아닙니다. – Tom

답변

0
Scanner sc = new Scanner(System.in); 
    int v=sc.nextInt(); 
    int s=sc.nextInt(); 
    // V variable becomes row and S variable come column, since you already know row length and column length you can use same for looping 
    int[][] n = new int [v][s]; 

    for (int i = 0; i < v; i++) { 
     for (int j = 0; j < s; j++) { 
      n[i][j] = sc.nextInt(); 
     } 
    } 

    // If you want to print last value 
    System.out.print(n[v-1][s-1]); 

배열 인덱스는 0으로 시작하므로 배열 크기가 3이면 인덱스 0,1,2를 가질 수 있습니다. 당신이 인덱스로 3를 사용하는 경우 다음 오류가 여기에있다

1

나는 가정 당신이 당신의 쿼리에 게시 예외가 발생합니다 :

배열은 0에서 V-1과 0의에 연동된다
System.out.print(n[v][s]); 

당신이 배열 × 3,은 다음과 같이 표시가있는 경우 -1

: 그래서 당신은 마지막 요소를 얻으려면

v[0]s[0] v[0]s[1] v[0]s[2] 
v[1]s[0] v[1]s[1] v[1]s[2] 
v[2]s[0] v[2]s[1] v[2]s[2] 

을, 당신은 작성해야 :

,
System.out.print(n[v-1][s-1]); 
관련 문제