我正在打印一个从每一列中递增的网格,我需要最后一列没有任何逗号。我很熟悉传统的栅栏桩问题,我知道如何用一个基本的循环来解决它。但是当涉及到嵌套循环时,我迷失了方向。有什么想法吗?谢谢
我试着在前面而不是后面加上逗号,并在循环开始之前植入一个"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发布于 2014-09-24 21:31:57
在第一个元素之后添加逗号的一种简单方法是使用变量。
String sep = "";
for (int j = i, lim = cols * rows; j <= lim; j += rows){
System.out.print(sep + j);
sep = ", ";
}
System.out.println();发布于 2014-09-24 21:37:58
最好的方法是使用布尔标志。这样,您就可以更改循环变量和条件,而不会破坏任何东西。
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();
}
}发布于 2014-09-24 21:43:01
一种不依赖于任何if语句的选项。您可以打印出第一个场景i,然后遍历j=i+行。
问题已被分解为初始操作、迭代操作和最终操作,以解决在终端出现的独特场景。
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
}
}https://stackoverflow.com/questions/26026798
复制相似问题