嵌套For循环,替换If语句

时间:2018-03-23 23:58:35

标签: java for-loop nested-loops

我最近一直在练习嵌套for循环。我尝试建立一个从(0,0)到(5,5)的5x5坐标块。每行将上升到y = 5,然后开始一个新行。

这是我构建的代码,它做了我想要它做的事情,唯一的问题是我必须使用if语句。是否有另一个for循环我可以使用它来使我不必使用if语句?

public class NestedLoops3 {
public static void main(String[] args) {

    for(int counter =0;counter<6;counter++) {
        for(int counter2 = 0;counter2<6;counter2++)
             {  
            System.out.print("("+counter+","+counter2+")");
            if(counter2==5) {
                System.out.println();
            }
    }
}
}
}

现在它正是按照我的意图完成的,但我只是想看看是否可以用另一个for循环替换if语句。

4 个答案:

答案 0 :(得分:2)

是。在嵌套循环之后移动println。像,

for (int counter = 0; counter < 6; counter++) {
    for (int counter2 = 0; counter2 < 6; counter2++) {  
        System.out.print("(" + counter + "," + counter2 + ")");
    }
    System.out.println();
}

答案 1 :(得分:0)

在嵌套for循环

之外调用System.out.println();

答案 2 :(得分:0)

我不建议用for循环写一个if语句:)

在循环工作后编写新行时,对于方形网格,可以使用单个循环并计算行和列

int size = 5;

for(int counter =0;counter<(size*size)+1;counter++) {
    int col = counter % size;
    int row = counter / size;
    System.out.printf("(%d, %d) ", row, col);
    if(col == size) {
        System.out.println();
    }
}

答案 3 :(得分:0)

是的,有可能:

public class NestedLoops3 {
    void main(String[] args) {
        for(int counter =0;counter<6;counter++) {
            for(int counter2 = 0;counter2<6;counter2++) {  
                System.out.print("("+counter+","+counter2+")");
                for (; counter2 == 5; ) {
                    System.out.println();
                    break;
                }
            }
        }
    }
}

但我不明白这样做的理由。 for循环的中间部分是一个条件,可以用于此目的。为了避免副作用,我放弃了将counter2设置为6,例如,在没有break语句的情况下中断循环,但由于counter2的范围有限,这也是有效的:

            for(int counter2 = 0;counter2<6;counter2++) {  
                System.out.print("("+counter+","+counter2+")");
                for (; counter2 == 5; counter2=6) {
                    System.out.println();
                }
            }

由于这种风格非常罕见,如果有人试图扩展代码,设置中间循环以运行到7,则容易出错。

但可能,是的,是的。

输出:

-> main (null) 
(0,0)(0,1)(0,2)(0,3)(0,4)(0,5)
(1,0)(1,1)(1,2)(1,3)(1,4)(1,5)
(2,0)(2,1)(2,2)(2,3)(2,4)(2,5)
(3,0)(3,1)(3,2)(3,3)(3,4)(3,5)
(4,0)(4,1)(4,2)(4,3)(4,4)(4,5)
(5,0)(5,1)(5,2)(5,3)(5,4)(5,5)
相关问题