2014-07-07 31 views
0

我需要這個練習有助於爪哇 - 少見類型的多維數組

考慮你有二維數組

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]); 

    }' 

Thx尋求幫助。根據要求

+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

你可以嘗試這樣的事: (這是未經測試的co因爲我直接寫在這裏)

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++; 
} 

它應該給出正確的格式。