Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从多维数组中打印出每个数字,最后一个数字后不加逗号?_Java_Arrays_Loops_Iteration - Fatal编程技术网

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("[\\]\\[]",""));
}