阵列比较测试

时间:2013-11-18 00:31:31

标签: arrays 2d

这给了很多麻烦。我不明白为什么测试失败了。 arrayToString应该获取array1的值并将其存储,以便与correctAnswer进行比较。

public static String arrayToString(int[][] a) {
    String string = "";
    for (int row = 0; row < a.length; row++) {
        for (int col = 0; col < a[0].length; col++) {
            string += a[row][col] + " ";
        }
        string += "\n";
    }
    return string;
}

主要方法。

public static void main(String[] args){

    private static int[][] array1 = { 
        {3, 2, 1, 1},
        {2, 5, 6, 2},
        {1, 2, 9, 8}
    };

    String methodCallResult, correctAnswer;
        System.out.println("Testing arrayToString method:");
        methodCallResult = FindTheSums.arrayToString(array1);
        correctAnswer = "3 2 1 1\n2 5 6 2\n1 2 9 8";
        if(methodCallResult.equals(correctAnswer)){
            System.out.println("arrayToString(array1) test passed");
        }
        else{
            System.out.println("arrayToString(array1) test failed");
        }
    }

2 个答案:

答案 0 :(得分:1)

测试失败,因为每个字母后面都有一个空格。你不在这里。

correctAnswer = "3 2 1 1\n2 5 6 2\n1 2 9 8";

                       ^^        ^^

string += a[row][col] + " ";

                  space ^^

这将匹配

correctAnswer = "3 2 1 1 \n2 5 6 2 \n1 2 9 8 ";

                  space ^^   space^^   space^^

编辑:方法更改的可能解决方案

public static String arrayToString(int[][] a) {
    String string = "";
    for (int row = 0; row < a.length; row++) {
        for (int col = 0; col < a[0].length; col++) {
            if (col == a[0].length - 1) {  // add the if statement to check for
                string += a[row][col];     // end of row. End of row adds no space.
            } else {
                string += a[row][col] + " ";
            }
        }
        string += "\n";
    }
    return string;
}

答案 1 :(得分:0)

您正在转换结束时添加空格。

for (int row = 0; row < a.length; row++) {
    for (int col = 0; col < a[0].length; col++) {
        string += a[row][col] + " ";
                                ^^^
    }
    string += "\n";
}

因此,correctAnswear应为3 2 1 1 \n2 5 6 2 \n1 2 9 8;