日期:2014-05-20  浏览次数:20723 次

求二维数组算法
有数组:
String   a[][]={{ "10 "},{ "20 "},{ "31 ", "32 ", "33 "}};
String   b[][]={{ "11 ", "12 ", "13 "},{ "21 "},{ "41 ", "42 ", "43 "}};

如何打印出:
10==> 11
10==> 12
10==> 13

20==> 21

31==> 41
32==> 42
32==> 43

------解决方案--------------------
题意不太清楚,但这样应该可以按要求输出:

for(int i=0; i < a.length; i++){
for(int j=0; j < b[i].length; j++){
System.out.println( (a[i].length < j ? a[i][a[i].length], a[i][j]) + "==> " + b[i][j]);
}
}
------解决方案--------------------
for(int i=0;i <a.length;i++){
for(int j =0;j <b[i].length;j++){
System.out.println(a[i].length <b[i].length?a[i][a[i].length-1]+ "==> "+b[i][j]:a[i][j]+ "==> "+b[i][j]);
}
}
------解决方案--------------------
楼上的方法貌似不行,我试了试会报错的。

public static void main(String[] args) {
  String a[][] = { { "10 " }, { "20 " }, { "31 ", "32 ", "33 "} };
  String b[][] = { { "11 ", "12 ", "13 " }, { "21 " }, { "41 ", "42 ", "43 " } };
  
  for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < a[i].length; j++) {
      if(a[i].length != b[i].length) {
        for (int k = 0; k < b[i].length; k++) {
          System.out.println(a[i][j] + " ==> " + b[i][k]);
        }
      }else{
        System.out.println(a[i][j] + " ==> " + b[i][j]);
      }
    }
    System.out.println();
  }
}
------解决方案--------------------
是啊,楼主描述得不是十分清楚,可能会出现两个对三个的情况,怎么处理?
------解决方案--------------------
String a[][] = { { "10 " }, { "20 " }, { "31 ", "32 ", "33 " } };
String b[][] = { { "11 ", "12 ", "13 " }, { "21 ", "22 " }, { "41 ", "42 ", "43 " } };
for (int i = 0; i < a.length; i++) {
if(i > = b.length) continue;
int len = a[i].length > b[i].length ? a[i].length : b[i].length;
for (int j = 0; j < len; j++) {
System.out.println(a[i][j%a[i].length] + "==> " + b[i][j%b[i].length]);
}
}