我需要这个练习的帮助
考虑你有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|
我曾尝试使用Comparator
这是代码:
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 :(得分: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|
答案 1 :(得分: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|
答案 2 :(得分: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++;
}
它应该给出正确的格式。