理解Java中的for循环

thi*_*ker -1 java for-loop

我是Java的新手.
我似乎无法理解为什么这两个代码产生不同的输出.

请向我解释一下.
有什么区别y<=x;y<=5;.正如你所看到的那样x是5,我不明白为什么我得到不同的输出.

for (int x = 0; x < 5; x++) {
    for (int y = 1; y <=x ; y++) {
        System.out.print("x");
    }

    for (int g = 4; g >= x; g--) {
        System.out.print("*");
    }                       
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

输出:

*****

x****

xx***

xxx**

xxxx*
Run Code Online (Sandbox Code Playgroud)

码:

for (int x = 0; x < 5; x++) {
    for (int y = 1; y <= 5; y++) {
        System.out.print("x");
    }

    for (int g = 4; g >= x; g--) {
        System.out.print("*");
    }                       
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

输出:

xxxxx*****

xxxxx****

xxxxx***

xxxxx**

xxxxx*
Run Code Online (Sandbox Code Playgroud)

Pit*_*ers 9

基本上主要区别在于这一行:

for(int y=1; y<=x; y++)
Run Code Online (Sandbox Code Playgroud)

RESP.

for(int y=1; y<=5; y++)
Run Code Online (Sandbox Code Playgroud)

循环执行的次数不同.即在第一种情况下它是可变的(因此'x'的数量增加),在第二种情况下它是固定的(每次打印5'x').

(编辑:错字)


Iwa*_*993 5

x从0开始,所以第一次迭代有条件y<=0,第二次迭代有y<=1等等..直到y<=5

虽然第二个将y<=5在每次迭代中都有,这就是为什么你在每一行得到xxxxx.