创建一个deepArray2String方法,该方法需要一个2D int数组'a1'并返回其字符串表示形式,可以将其写入控制台。

我已经尝试了一些逻辑,但是却遇到此错误:

tester.java:18:错误:类型不兼容:StringBuffer无法转换为String
   返回结果;
           ^

public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}


System.out.println(deepArray2String(new int [] [] {{1},{2},{4}}));

输出应为[1],[2],[4]

System.out.println(deepArray2String(new int [] [] {{1},{2,3}}));

输出应为[[1],[2、3]]

System.out.println(deepArray2String(new int [] [] {})));

输出应为[]

System.out.println(deepArray2String(new int [] [] {{5,3},{1},{-1,1}}));

输出应为[[5,3],[1],[-1,1]]

最佳答案

无需重新发明轮子,Java已经在java.util.Arrays中构建了一个静态方法来执行此操作。 Autoboxing表示它将与任何原始类型的数组一起使用。

import java.util.Arrays;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExampleTest {

    @Test
    public void test() {
        log.info(Arrays.deepToString(new int[][] { { 1 }, { 2 }, { 4 } }));
        log.info(Arrays.deepToString(new int[][] { { 1 }, { 2, 3 } }));
        log.info(Arrays.deepToString(new int[][] {}));
        log.info(Arrays.deepToString(new int[][] { { 5, 3 }, { 1 }, { -1, 1 } }));
    }
}


结果

[main] INFO coaching.arrays.ExampleTest - [[1], [2], [4]]
[main] INFO coaching.arrays.ExampleTest - [[1], [2, 3]]
[main] INFO coaching.arrays.ExampleTest - []
[main] INFO coaching.arrays.ExampleTest - [[5, 3], [1], [-1, 1]]


参数的工作方式完全相同。

@Test
public void test() {
    int[][] a = new int[][] { { 1 }, { 2 }, { 4 } };
    log.info(Arrays.deepToString(a));

    int[][] a2 = new int[][] { { 1 }, { 2, 3 } };
    log.info(Arrays.deepToString(a2));

    int[][] a3 = new int[][] {};
    log.info(Arrays.deepToString(a3));

    int[][] a4 = new int[][] { { 5, 3 }, { 1 }, { -1, 1 } };
    log.info(Arrays.deepToString(a4));
}

10-06 01:48