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,
我想用每行中的最后一个数字删除尾随逗号,但我没有变量作为持有它们的字符串,只是一个print语句。有没有办法做到这一点?
答案 0 :(得分: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();
}
}
args 3,6的输出将是:
1, 4, 7, 10, 13, 16 2, 5, 8, 11, 14, 17 3, 6, 9, 12, 15, 18
答案 1 :(得分:1)
System.out.print(i + rows * k);
if (k < cols - 1) {
System.out.print(", ");
}
我会测试k
不是0
并在逗号不是像
if (k != 0) {
System.out.print(", ");
}
System.out.print(i + rows * k);
答案 2 :(得分:-1)
如果您的代码难以理解,效率并不重要。部分问题围绕着您尝试将字符串组合与输出组合的方式。你应该完全分开这些东西:
static void printGrid(int rows, int cols) {
System.out.println(getGrid(rows, cols));
}
static String getGrid(int rows, int cols) {
StringBuilder b = new StringBuilder();
int totalNum = rows * cols;
for (int i = 1; i <= rows; i++) {
for (int k = 0; k < cols; k++) {
b.append(i + rows * k).append(", ");
}
b.delete(b.size()-2,b.size());
b.append('\n');
}
return b.toString();
}
Alterantely,您可以使用Guava Joiner
,或者在Java 8中使用Collectors.joining