2D阵列在比较期间不打印最后一个元素

时间:2014-02-05 00:13:06

标签: java arrays multidimensional-array

我正在尝试将原始2d数组中的行替换为更新的2d数组。问题是它在更换期间不会存储最后一个元素。

这是我的代码:

String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};

    String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};

    for (int i = 0; i < updatedArray.length;i++ ) {
        for (int j = 0; j < updatedArray[i].length; j++){
            for(int x = 0; x < originalArray.length;x++){
                for(int z = 0; z < originalArray[x].length;z++){
                if(originalArray[x][0].equals(updatedArray[i][0])) {
                    updatedArray[i][j] = originalArray[x][j];
                    System.out.println("There's a match!!");
                }else{
                    System.out.println("No match!");
                }
            }
            }
        }   
    }

    System.out.println("originalArray:");
    System.out.println(Arrays.deepToString(originalArray));
    System.out.println("updatedArray:");
    System.out.println(Arrays.deepToString(updatedArray));

例如,最初在最后一行“purple”中的updatedArray有{"purple","a","b","c"}。当使用来自originalArray的值进行替换时,上面的代码只输出:

  

... [紫色,nn,mm,bb]

这是错误的,因为它没有添加最后一个元素“hello”。它应输出:

  

... [紫色,nn,mm,bb,你好]

我知道问题出在这一行:

  

updatedArray [i] [j] = originalArray [x] [j];

问题无论我试图将originalArray [x] [j]更改为originalArray [x] [ z ] ......它会搞砸一切。

有关于此的任何想法吗?仍试图获得二维阵列的精神。

2 个答案:

答案 0 :(得分:0)

如果存在匹配,则可以将整个数组设置为原始数组,而不是尝试将updatedArray中的每个元素设置为原始数组中的相应元素。

String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};

String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};

for (int i = 0; i < updatedArray.length;i++ ) {
    for (int j = 0; j < originalArray.length; j++){
        if(originalArray[j][0].equals(updatedArray[i][0])) {
            updatedArray[i] = originalArray[j];
            System.out.println("There's a match!!");
        }else{
            System.out.println("No match!");
        }
    }   
}

答案 1 :(得分:0)

问题是您如何选择迭代updatedArray的维度,这些维度与originalArray的维度不同。

让我们看一下i = 2的情况,即紫色的'row':

for (int j = 0; j < updatedArray[i].length; j++){ 

updatedArray[i=2].length = 4

更新时间:

index =   0      , 1 , 2 , 3
        {"purple","a","b","c"}

原文:

index =   0      , 1 ,  2 ,  3  , 4
        {"purple","nn","mm","bb","hello"}

因此,因为j总是&lt; 4它永远不能用于索引originalArray [x] [4] =“你好”

危险:此代码也无法处理您需要为updatedArray扩展紫色数组的事实。 Java可能会为你解决这个问题,但我不相信它能以这种方式工作。

建议:
- 在将数据从originalArray复制到updatedArray之前,比较每行的长度并在必要时分配额外的内存 - 如果可能的话,只需复制原始和更新之间的整行。