所以我试图用括号和逗号打印一个二维数组。这是我的代码:
public class ArrayPrinter {
public static int printArray(int[][] arr) {
{
System.out.println("["); {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j]);
if (j < arr.length) {
System.out.print(", ");
}
}
System.out.println();
}
}
System.out.println("]");
}
return 0;
}
public static void main(String[] args) {
int[] oneD = {5, 6, 7, 8
};
printArray(oneD);
System.out.println(); {
int[][] twoD = {
{2, 4, 6, 8},
{8, 7, 9, 1},
{3, 5, 1, 2}
};
printArray(twoD);
System.out.println();
}
int[][] twoD2 = {
{1, 2},
{3, 4, 5},
{6},
{7, 8, 9}
};
printArray(twoD2);
System.out.println();
}
public static void printArray(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
这是我现在的结果:
[5, 6, 7, 8]
[
2, 4, 6, 8
8, 7, 9, 1
3, 5, 1, 2
]
[
1, 2,
3, 4, 5,
6,
7, 8, 9,
]
这是我想要的结果:
[5, 6, 7, 8]
[
[2, 4, 6, 8]
[8, 7, 9, 1]
[3, 5, 1, 2]
]
[
[1, 2]
[3, 4, 5]
[6]
[7, 8, 9]
]
我希望用括号和逗号打印数组,但每个一维数组应该在一个单独的行上。
感谢任何帮助。谢谢!
答案 0 :(得分:2)
为什么你不能像这样使用Arrays.toString(oneD)
和Arrays.deepToString(twoD)
:
int[] oneD = {5, 6, 7, 8};
int[][] twoD = {{2, 4, 6, 8}, {8, 7, 9, 1}, {3, 5, 1, 2}};
int[][] twoD2 = {{1, 2}, {3, 4, 5}, {6}, {7, 8, 9}};
System.out.println(Arrays.toString(oneD));
System.out.println(Arrays.deepToString(twoD));
System.out.println(Arrays.deepToString(twoD2));
这可以告诉你:
[5, 6, 7, 8]
[[2, 4, 6, 8], [8, 7, 9, 1], [3, 5, 1, 2]]
[[1, 2], [3, 4, 5], [6], [7, 8, 9]]
别忘了导入你的图书馆:
import java.util.Arrays;
答案 1 :(得分:1)
最简单的2D数组方法实现。只需使用1D方法:
public static void printArray(int[][] grid) {
System.out.println("[");
for (int[] arr: grid) {
printArray(arr);
}
System.out.println("]");
}
请注意,我不会在2D网格的行之间放置一条空行。如果你想要你的确切输出,只需在for循环中添加一个空的println()
:
public static void printArray(int[][] grid) {
System.out.println("[");
for (int[] arr: grid) {
printArray(arr);
System.out.println();
}
System.out.println("]");
}
答案 2 :(得分:1)
围绕[]
public static int printArray (int[] [] arr) {
System.out.println("["); {
for (int i = 0; i < arr.length; i++) {
System.out.print("[");
for(int j = 0; j < arr[i].length; j++)
{System.out.print(arr[i][j]);
if (j<arr[i].length-1) {
System.out.print(", ");}
}
System.out.println("]");
}
}
System.out.println("]");
return 0;
}
答案 3 :(得分:1)
for (int i = 0; i < arr.length; i++) {
System.out.print("[");
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j]);
if (j<arr.length) {
System.out.print(", ");
} else {
System.out.println();
}
}
System.out.print("]");
}
用上面的那些替换你的两个for循环。您需要将括号附加并添加到主数组中的每个数组。希望这有帮助!