public static void printGrid(int rows, int cols) {
int totalNum = rows * cols;
for (int i = 1; i <= rows; i++) {
for (int k = 0; 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,
I want to remove the trailing commas by the last numbers in each line, but I do not have a variable as a string holding them, just a print statement. Is there any way to do this?
解决方案
Simply, print it only when needed:
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();
}
}
Output for args 3, 6 would be:
1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
3, 6, 9, 12, 15, 18