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语句.有没有办法做到这一点?
只需在需要时打印:
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
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |