gpt4 book ai didi

java - 我必须创建一个 deepArray2String 方法,该方法需要一个 2D int 数组 'x' 并返回其字符串表示形式

转载 作者:行者123 更新时间:2023-11-29 08:22:32 25 4
gpt4 key购买 nike

创建一个 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));
}

关于java - 我必须创建一个 deepArray2String 方法,该方法需要一个 2D int 数组 'x' 并返回其字符串表示形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56383462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com