2013-12-17 4 views
2

좋아, 그럼 내 내부 루프에 대한 약간의 논리 오류가 있다고 말했습니다. 외관상으로는 [2] [2] 배열이 2X3 요소 또는 3X2 요소 였을 경우 누군가가이 약간의 문제를 해결하는 방법을 말해 줄 수 있습니까? 배열의 for 루프와의 논리적 오류

for (int i = 0; i < country.length; i++) { 

        // note the change here 
    for (int j = 0; j < country[i].length; j++) { 
     // ... 
    } 
} 

그렇지 않으면, 내부 루프만큼 그것을 필요로 카운트하지 않습니다에

public static void dispArr(String [][] country){ 
    for(int i= 0; i<country.length; i++){ // both for loops count from 0 to 1 which are the only numbers required for this given array 
     for(int j= 0; j<country.length; j++){ 
      System.out.print(country[i][j]); //this will output [0][0],[0][1],[1][0] and[1][1] as identified above. 
     } 

     System.out.println("\n"); //create space between both 
    } 
} 
+0

내부 루프에'country [i] .length' 시도 –

+0

대단히 감사합니다! – user3111329

답변

8

변경을. 간단한 예를 들어

, 당신이 있다면이 :

[[1, 2, 3], [4, 5, 6]] 

그것은 (원래 코드)가 될 것입니다 :

for (int i = 0; i < 2; i++) { 

       // oh no! not counting far enough 
    for (int j = 0; j < 2; j++) { 
     // ... 
    } 
} 

당신은 내부 배열의 길이 을해야 당신을 반복하고 내부 배열이 이 아니고이 적당합니다.

0

country.length은 첫 번째 측정 기준 만 제공합니다. country[i].length은 두 번째 차원을 제공합니다.

+0

'country.length [i]'??? 응? – Doorknob

+0

바보 같은 맞춤법 오류 – Dom

0

행렬의 첫 번째 차원 통해 내부 루프의 반복, 그리고 아마도 대신

for (int j=0; j < country[i].length; j++) { ... 

해야한다. country 뒤에 [i]을 적어 둡니다.

건배,

2

Java에서 2 차원 배열은 본질적으로 배열의 배열입니다. 따라서 두 번째 셀을 계산할 때 첫 번째 차원 (배열)의 인덱스를 넣어야합니다.

public static void dispArr(String [][] country){ 
    for(int i= 0; i<country.length; i++){ // both for loops count from 0 to 1 which are the only numbers required for this given array 

     for(int j= 0; j<country[i].length; j++){ 

      System.out.print(country[i][j]); //this will output [0][0],[0][1],[1][0] and[1][1] as identified above. 
     } 

     System.out.println("\n"); //create space between both 
    } 
}