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,
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?
Efficiency doesn't matter if your code is hard to understand. Part of the problem revolves around the way you are attempting to combine string composition with output. You should seperate those things entirely:
Alterantely, you could use the Guava
Joiner
, or in Java 8 you could useCollectors.joining
Simply, print it only when needed:
Output for args 3, 6 would be:
While you might test after you print in a post-condition as suggested by @MightyPork in that answer
I would test that
k
is not0
and print the comma when it isn't in a pre-condition like