简体   繁体   English

为什么下面的程序打印“Hello”三遍而不是两次?

[英]Why the following program printing "Hello" three time and not two?

I am learning java nowadays, and while going through loops in java, I am stuck here, I am unable to understand why the following program is printing "Hello" three times.我现在正在学习java,在java中遍历循环时,我被困在这里,我无法理解为什么下面的程序打印“Hello”三遍。 can you please explain?你能解释一下吗?

public class Helloworld {

    public static void main(String[] args) {
        for (int i =1; i<=2; i++ ) {
            for (int j =1; j<=i ; j++) {
                System.out.println("Hello");        
            }   
        }
    }
}

for loop iterations: for循环迭代:

i=1
    j=1 — prints "Hello"
    j=2 — breaks out of inner loop, `j <= i` is false.
i=2
    j=1 — prints "Hello"
    j=2 — prints "Hello"
    j=3 — breaks out of inner loop, `j <= i` is false.

This is what happens when the above code is run.这就是运行上述代码时发生的情况。

To understand why, change要了解原因,请更改

System.out.println("Hello"); 

to

System.out.println("Hello: i = " + i + ", j = " + j); 

compile and run it again, and look carefully at the values of i and j printed out.再次编译运行,仔细查看打印出来的ij的值。

Basically, in the second iteration of the outer loop, the inner loop runs twice.基本上,在外循环的第二次迭代中,内循环运行了两次。


If you cannot compile and run the program, there is another way to understand the behavior.如果您无法编译和运行该程序,则可以通过另一种方式来理解该行为。 Hand execute it.手动执行。

Get a pencil an piece of paper, draw a table with a column for each variable.拿一支铅笔一张纸,画一张表格,每个变量都有一列。 Each time a variable is assigned to / modified (eg i = 0 or i++ ) add a new row to the table with the current values of all of the variables.每次将变量分配给/修改(例如i = 0i++ )时,都会向表中添加一个新行,其中包含所有变量的当前值。 When you have a test (eg i<=2 ) read the variable's value from the latest row in the table.当您进行测试时(例如i<=2 )从表中的最新行读取变量的值。

After some practice you will be able to do this in your head.经过一些练习,您将能够在头脑中做到这一点。 After more practice you will be able to read the code (like you read English text, or mathematical notation) and reason about what the code does.经过更多练习,您将能够阅读代码(就像阅读英文文本或数学符号一样)并推理代码的作用。

Or use a debugger :-)或者使用调试器:-)

Sometimes when learning loops, writing small loops on paper can help.有时在学习循环时,在纸上写小循环会有所帮助。

Here you habe a nested loop using variables i and j.在这里,您可以使用变量 i 和 j 构建一个嵌套循环。

First, the inner loop, j=1, and 1 is less than or equal to 1(i), so it prints.首先,内循环,j=1,1小于等于1(i),所以打印。 Then j++.然后j++。

j is now 2, which is not less than or equal to 1, ending inner loop cycle. j 现在是 2,不小于或等于 1,结束内循环循环。 Now back to outer loop, i++,现在回到外循环,i++,

i is now 2. Inside the inner loop- j=1, less than or equal to 2, so second print. i 现在是 2。在内循环中 - j=1,小于或等于 2,所以第二次打印。 Now j++.现在j++。 Condition still true, as j(as 2) is still less than or equal to 2, so third print.条件仍然成立,因为 j(as 2) 仍然小于或等于 2,所以第三次打印。

Hope this debugging method helps you.希望这个调试方法对你有帮助。

You have two loops.你有两个循环。 The outer i loop runs twice, but inner j loop depends on the value of i with the j<=i part.外部i循环运行两次,但内部j循环取决于带有j<=i部分的i值。 So for the first i loop, j runs once, and the second i loop j runs twice, so three times all up.所以对于第一个i循环, j运行一次,第二个i循环j运行两次,所以总共运行了 3 次。

This has to do with the nested looping.这与嵌套循环有关。 There's (2) loops to pay attention to here.这里有 (2) 个循环需要注意。 For each iteration of the outer loop (i), the inner loop (j) may run multiple times.对于外循环 (i) 的每次迭代,内循环 (j) 可能会运行多次。 If you change the output to output the iterators, it will give you some visibility into this property.如果您将输出更改为输出迭代器,它将为您提供对该属性的一些可见性。

System.out.println("i:"+i+"  j:"+j);

OUTPUT: $javac HelloWorld.java
i: 1  j:1
i: 2  j:1
i: 2  j:2

If you want to get a more detailed view on nested looping, here's a good video series I'd recommend: Nested Looping (The Coding Train)如果你想更详细地了解嵌套循环,这里有一个很好的视频系列我推荐:嵌套循环(编码火车)

Hope this helps!希望这可以帮助!

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

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