围栏发布问题

时间:2014-09-24 21:26:11

标签: java for-loop

我正在打印一个网格,每列向下递增,我需要最后一列不要有任何逗号。我熟悉经典的围栏问题,我知道如何用基本循环来解决它。但是当涉及嵌套循环时,我迷失了。有任何想法吗?感谢

我尝试在前面而不是后面添加逗号并在循环开始之前插入“帖子”,但它永远不会有效。

这是我的代码:

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

4 个答案:

答案 0 :(得分:1)

看起来你只想跳过打印第一个逗号,所以你可以尝试一下这一行(作为内循环的主体):

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

答案 1 :(得分:0)

在第一个元素之后添加逗号的简单方法,前提是有另一个元素是使用变量。

String sep = "";
for (int j = i, lim = cols * rows; j <= lim; j += rows){
    System.out.print(sep + j);
    sep = ", ";
}
System.out.println();

答案 2 :(得分:0)

执行此操作的最佳方法是使用布尔标志。这样,您可以在不破坏任何内容的情况下更改循环变量和条件。

public static void printGrid(int rows, int cols){
    for (int i = 1; i <=rows; i++){
        boolean isFirst = true;
        for (int j = i; j<=cols*rows; j=j+rows){
            if (isFirst) {
              System.out.print(j);
              isFirst = false;
            }
            else {
               System.out.print(", " + j);
            }
        }
        System.out.println();
    }
}

答案 3 :(得分:0)

不依赖任何if语句的选项。您可以打印出第一个场景,i,然后遍历j = i + rows。

问题已经分解为初始操作,迭代操作和最终操作,以解决在终点发生的独特方案。

public static void printGrid(int rows, int cols) {
    for (int i = 1; i <= rows; i++) {
        System.out.print(i); // initial operation
        for (int j = i + rows; j <= cols * rows; j = j + rows) {
            System.out.print(", " + j);
        } // iterative operation
        System.out.println(); // final operation
    }
}