删除没有字符串变量的尾随逗号Java?

Lom*_*ang -1 java comma trailing

public static void printGrid(int rows, int cols) {
    int totalNum = rows * cols;
    for (int i = 1; i <= rows; i++) {
        for (int k = 0; k < cols; k++) {
            System.out.print(i + rows * k + ", ");
        } System.out.println();      
    }
}

Outputs = 1, 4, 7, 10, 13, 16, 
          2, 5, 8, 11, 14, 17, 
          3, 6, 9, 12, 15, 18, 
Run Code Online (Sandbox Code Playgroud)

我想删除每行中最后一个数字的尾随逗号,但我没有变量作为持有它们的字符串,只是一个print语句.有没有办法做到这一点?

Mig*_*ork 8

只需在需要时打印:

public static void printGrid(int rows, int cols) {
    int totalNum = rows * cols;
    for (int i = 1; i <= rows; i++) {
        for (int k = 0; k < cols; k++) {
            System.out.print(i + rows * k);
            if (k < cols - 1) System.out.print(", ");
        }
        System.out.println();      
    }
}
Run Code Online (Sandbox Code Playgroud)

args 3,6的输出将是:

1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
3, 6, 9, 12, 15, 18

  • @MightyPork我猜Desolator误解了这个问题,并认为OP只想要删除最后一个逗号(在你的例子中是'18`). (2认同)