本文介绍了删除不带字符串变量的结尾逗号Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
推荐答案
简单来说,仅在需要时才打印:
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();
}
}
参数3、6的输出为:
1, 4, 7, 10, 13, 16
2, 5, 8, 11, 14, 17
3, 6, 9, 12, 15, 18
这篇关于删除不带字符串变量的结尾逗号Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!