Java 从多维数组中打印出每个数字,最后一个数字后不加逗号?
我试图弄清楚如何在一条单行线上显示多维数组中同一“行”中的每个数字,并用逗号分隔它们 这就是我如何声明多维数组的Java 从多维数组中打印出每个数字,最后一个数字后不加逗号?,java,arrays,loops,iteration,Java,Arrays,Loops,Iteration,我试图弄清楚如何在一条单行线上显示多维数组中同一“行”中的每个数字,并用逗号分隔它们 这就是我如何声明多维数组的 int[][] grid = { {1, 2, 3}, {4}, {5, 6}, {123, 4567, 78901, 234567} }; 这是我用来在单独一行上显示每个“行”的循环,它们之间有逗号: for(int[] row: grid){ for(int
int[][] grid = {
{1, 2, 3},
{4},
{5, 6},
{123, 4567, 78901, 234567}
};
这是我用来在单独一行上显示每个“行”的循环,它们之间有逗号:
for(int[] row: grid){
for(int col: row){
System.out.print(col + ", ");
}
System.out.println();
}
或者:
for(int row = 0; row < grid.length; row++){
for(int col = 0; col < grid[row].length; col++){
System.out.print(grid[row][col] + ", ");
}
System.out.println();
}
如何使最后一个数字不带逗号?非常简单、容易,您可以:
for(String s : Arrays.deepToString(grid).split("(?<=]), "))
{
System.out.println(s.replaceAll("[\\]\\[]",""));
}
for(字符串s:Arrays.deepToString(grid).split((col
Quick:System.out.print((col>0?,“:”)+grid[row][col col]);
(可能有更好的选项)
for(String s : Arrays.deepToString(grid).split("(?<=]), "))
{
System.out.println(s.replaceAll("[\\]\\[]",""));
}