简体   繁体   English

为什么这个println不能整个执行?

[英]Why isn't this println being executed with the entire body?

I'm new to programming and trying to understand this nested for loop completely. 我是编程的新手,试图完全理解嵌套的for循环。 The println is part of the body of the inner loop. println是内部循环主体的一部分。 However, it is not being executed with the inner loop iteration. 但是,它不是与内循环一起执行的。 I don't want to execute it, but I'm just trying to understand why the inner loop body isn't executed completely? 我不想执行它,但是我只是想了解为什么内部循环体没有完全执行?

int rowNum, colNum;
    for (rowNum = 1; rowNum <= 3; rowNum++) 
    {
     for (colNum = 1; colNum <= 2; colNum++) 
            System.out.print(" rowNum: " + rowNum + " colNum: " + colNum);
        System.out.println();

    }

If the println() were executed with the body I would get something like this: 如果将println()与主体一起执行,我将得到以下内容:

 rowNum: 1 colNum: 1
 rowNum: 1 colNum: 2
 rowNum: 2 colNum: 1
 rowNum: 2 colNum: 2
 rowNum: 3 colNum: 1
 rowNum: 3 colNum: 2

Instead, I'm getting this: 相反,我得到了这个:

 rowNum: 1 colNum: 1 rowNum: 1 colNum: 2
 rowNum: 2 colNum: 1 rowNum: 2 colNum: 2
 rowNum: 3 colNum: 1 rowNum: 3 colNum: 2

Again, I just want to understand why, not how to fix it... Thanks! 再次,我只想了解原因,而不是如何解决...谢谢!

for loop execute only next 1 line if curly brackets are not provided. 如果未提供大括号,则for循环仅执行下一行。 if you give curly brackets between second for loop and after println();. 如果在第二个for循环之间和println();之后给出大括号。 you will get want you want. 你会想要的。

System.out.print(" xxx "); System.out.print(“ xxx”); System.out.println(); System.out.println();

this will give you xxx xxx xxx xxx 这会给你xxx xxx xxx xxx

because it is print println print 2 times then line comes. 因为它是print println print 2次,所以行来了。

edit first System.out.println(" rowNum: " + rowNum + " colNum: " + colNum); 编辑第一个System.out.println(“ rowNum:” + rowNum +“ colNum:” + colNum);

and remove second println. 并删除第二个println。

rowNum: 1 colNum: 1 rowNum: 1 colNum: 2 rowNum: 2 colNum: 1 rowNum: 2 colNum: 2 rowNum: 3 colNum: 1 rowNum: 3 colNum: 2 rowNum:1 colNum:1 rowNum:1 colNum:2 rowNum:2 colNum:1 rowNum:2 colNum:2 rowNum:3 colNum:1 rowNum:3 colNum:2

This is because you print 2 times before getting out of the loop and print a new line. 这是因为您要打印2次才能退出循环并打印新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM