简单的嵌套循环的例子 [英] Simple nested for loop example

查看:174
本文介绍了简单的嵌套循环的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在学习Java测试。惠斯特学习我遇到了一个小问题。



在这个循环中:

  for(int i = 1 ; i <= 3; i ++){
for(int j = 1; j <= 3; j ++){
System.out.println(i ++ j);




$ b $输出是:

  1 1 
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

我的问题是,我不明白当我读这段代码的时候,我一直认为它应该看起来像这样:

  1 1 
2 2
3 3

为什么不是这样?

解决方案

每一次我的迭代,你开始一个全新的迭代j。

所以,你开始我== 1,然后循环j == 1,2,3。然后我= 2,然后j = 1,2,3循环,等等。



一步一步,这将是有道理的。


Currently I am studying for my Java test. Whist studying I've come across a small problem.

In this for loop:

for ( int i=1; i <= 3 ; i++ ) {
    for (int j=1; j <= 3 ; j++ ) {
        System.out.println( i + " " + j );
    }
}

The output is:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

My problem is, I don't understand it. When I read this code I keep thinking it should look like this:

1 1
2 2
3 3

Why is this not the case?

解决方案

Each iteration of i, you're starting a completely new iteration of j.

So, you start with i==1, then j==1,2,3 in a loop. Then i==2, then j==1,2,3 in a loop, etc.

Step through it one step at a time, and it will make sense.

这篇关于简单的嵌套循环的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆