简体   繁体   English

有人可以向我解释为什么此嵌套循环函数以这种方式打印吗?

[英]Can someone explain to me why this nested loop function print this way?

So here is the code that runs: 所以这是运行的代码:

public static void main(String[] args) 
{
    for (int i=1; i<=6; i++) 
    {
        for (int j=1; j<=i; j++) 
        System.out.print("*");
        System.out.print("-");
    }
}

why does it print 为什么打印

*-**-***-****-*****-******- *-**-***-****-*****-******-

instead of 代替

* _ ** __ *** ___ **** ____ *****_____******______ * _ ** __ *** ___ **** ____ ***** _____ ****** ______

this is because didnt put your print("-") inside any of your inner loops, change your loop to : 这是因为没有将print("-")放入任何内部循环中,请将循环更改为:

for (int i=1; i<=6; i++) 
{
    for (int j=1; j<=i; j++) 
        System.out.print("*");
    for (int j=1; j<=i; j++) 
        System.out.print("-");

}

and your problem will fix. 这样您的问题就会解决。

System.out.print("-"); is not inside the inner loop. 不在内部循环内。 Therefore it's only printed once for each iteration of the outer loop. 因此,对于外循环的每次迭代仅打印一次。

This becomes clearer when you indent your code properly : 当您正确缩进代码时,这将变得更加清晰:

for (int i=1; i<=6; i++) 
{
    for (int j=1; j<=i; j++) 
        System.out.print("*");
    System.out.print("-");
}

Even if it was inside the inner loop (by adding curly braces), you'd still not get the output you expected, since you'll get one - after each * . 即使它在内部循环内(通过添加花括号),您仍将无法获得预期的输出,因为每个*后面都会有一个-

In order to get the output you expected, you need two inner loops : 为了获得您期望的输出,您需要两个内部循环:

for (int i=1; i<=6; i++) 
{
    for (int j=1; j<=i; j++) 
        System.out.print("*");
    for (int j=1; j<=i; j++) 
        System.out.print("-");
}

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

相关问题 有人可以告诉我这个嵌套循环中发生了什么吗? - Can someone explain to me what is going on within this nested loop? 有人能解释一下为什么只有字符串 s4 的打印结果是 10bab 吗? - Can someone explain me why the print of only string s4 turns out to be 10bab? 有人可以向我解释为什么我有此错误吗? - Can someone explain to me why I'm having this error? 有人可以解释一下这个 function 在 Java 中找到 BigInteger 的平方根吗? - Can someone explain me this function that finds the square root of an BigInteger in Java? 第二个while循环不断运行,有人可以解释为什么吗? - The second while loop is running endlessly can someone please explain why? 我无法打印出 0。有人可以告诉我为什么吗? - I can´t print out 0 . Can someone tell me why? 谁能给我解释一下Java中关于内存的嵌套for循环的行为? - Can anyone explain to me the behavior of a nested for loop in Java in regards to memory? 有人可以向我解释这种递归方法吗? - Can someone explain me this recursive method? 有人可以向我解释此nullPointerException错误的详细信息吗? - Can someone explain the details of this nullPointerException error to me? 有人可以解释一下这个小代码吗? - Can someone explain me this little code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM