我正在打印一个网格,该网格向下递增每列,并且我需要最后一列不包含任何逗号。我熟悉经典的栅栏杆问题,并且知道如何使用基本循环来解决它。但是当涉及到嵌套循环时,我迷失了。有任何想法吗?谢谢
我试图在循环开始之前在前面而不是后面加上逗号,并在循环开始之前添加一个“ post”,但是它始终无法解决。
这是我的代码:
public class Printgrid{
public static void main (String[] args){
printGrid(3, 6);
}
public static void printGrid(int rows, int cols){
for (int i = 1; i <=rows; i++){
for (int j = i; j<=cols*rows; j=j+rows){
System.out.print(", " + j);
}
System.out.println();
}
}
}
这是输出:
, 1, 4, 7, 10, 13, 16
, 2, 5, 8, 11, 14, 17
, 3, 6, 9, 12, 15, 18
最佳答案
看起来您只是想跳过打印第一个逗号,因此您可以按照以下方式尝试一些操作(作为内部循环的主体):
if (j > i) { // i.e. if we are not on the first iteration
System.out.print(", ");
}
System.out.print(j);
产生:
1,4,7,10,13,16
2、5、8、11、14、17
3、6、9、12、15、18