对多维数组进行罕见排序



我需要帮助做这个练习

假设你有一个2d数组

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

谢谢你的帮助

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|

正如@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|

你可以尝试这样做:(这是未经测试的代码,因为我直接在这里写的)

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

它应该给出正确的格式

相关内容

  • 没有找到相关文章

最新更新