2014-07-07 3 views
0

자바 - 드문 종류의 난이 연습에 도움이 필요 다차원 배열

는 2 차원 배열

String[][]myArray={ 
     {"0.0","0.1","0.2","0.3","0.4"}, 
     {"1.0","1.1","1.2","1.3"}, 
     {"2.0","2.1","2.2","2.3","2.4","2.5"} 
     }; 

을 고려하면 인쇄 할 :

0.0|1.0|2.0| 
0.1|1.1|2.1| 
0.2|1.2|2.1| 
0.3|1.3|2.3| 
0.4|2.4| 
2.5| 

내가 사용하는 것을 시도했다 비교기

여기에 코드 :

public static void main(String[] args) { 

    String[][]Array={ 
      {"0.0","0.1","0.2","0.3","0.4"}, 
      {"1.0","1.1","1.2","1.3"}, 
      {"2.0","2.1","2.2","2.3","2.4","2.5"} 
      }; 

    Arrays.sort(Array, new PorKolumn(2)); 

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

     String [] kol = Array[i]; 
     for(int j=0; j<kol.length; j++) { 
      System.out.print(kol[j] + " | "); 

     } 
     System.out.println(); 
    } 
    } 


} 

class PorKolumn implements Comparator{ 
    int Kolumny; 

    public PorKolumn(int Kolumny) { 
     this.Kolumny = Kolumny; 

    } 
    public int compare (Object o1, Object o2){ 
     String [] kol1 = (String []) o1; 
     String [] kol2 = (String []) o2; 

     return kol1[Kolumny].compareTo(kol2[Kolumny]); 

    }' 

아무 도움이 필요합니다. 요청에 따라

+0

그래서 각 배열을 정렬하려면 정렬 된 후 첫 번째 값을 기준으로 배열을 정렬 하시겠습니까? – nafas

+0

내부 배열을 세로로 인쇄하고 싶습니까? –

+0

정렬이 표시되지 않습니다. 내부 배열을 세로로 인쇄 한 다음 모든 것을 가능한 한 왼쪽으로 밀고 있습니다. – Teepeemm

답변

0
public static void print(String[][] a){ 
    int iRow = 0; 
    while(true){ 
     boolean done = false; 
     for(int iCol = 0; iCol < a.length; iCol++){ 
      if(iRow < a[iCol].length){ 
       System.out.print(a[iCol][iRow] + "|"); 
       done = true; 
      } 
     } 
     if(! done) break; 
     System.out.println(); 
     iRow++; 
    } 
} 

인쇄가 :

0.0|1.0|2.0| 
0.1|1.1|2.1| 
0.2|1.2|2.2| 
0.3|1.3|2.3| 
0.4|2.4| 
2.5| 
0

@Teepeemm 더 정렬이없는 언급 한 바와 같이 :

String[][]myArray={ 
     {"0.0","0.1","0.2","0.3","0.4"}, 
     {"1.0","1.1","1.2","1.3"}, 
     {"2.0","2.1","2.2","2.3","2.4","2.5"} 
     }; 

    int maxLength = 0; 
    for(int i = 0; i < myArray.length; i++) 
     if(maxLength < myArray[i].length) 
      maxLength = myArray[i].length; 

    for(int j = 0; j < maxLength; j++) { 
     for(int i = 0; i < myArray.length; i++) 
      if(j < myArray[i].length) 
       System.out.print(myArray[i][j] + "|"); 
     System.out.print("\n"); 
     } 
    } 

출력 :

0.0|1.0|2.0| 
0.1|1.1|2.1| 
0.2|1.2|2.2| 
0.3|1.3|2.3| 
0.4|2.4| 
2.5| 
0

당신은 이런 식으로 뭔가를 시도 할 수 있습니다 : (테스트되지 않은 공동 내가 여기 직접 작성했기 때문에).

int i = 0; 
boolean ongoing = true; 

while(ongoing){ 

    for(int j = 0; j < myArray.length; j++){ 
    if(myArray[j][i] == null){ 
     System.out.print("\t|"); 
     ongoing = false; 
     continiue; 
    } 
    ongoing = true; 
    System.out.print(myArray[j][i]+"\t|"); 
    } 
    System.out.print("\n"); 
    i++; 
} 

올바른 형식을 제공해야합니다.