印刷星星图案

我正在尝试打印如下所示的星形图案


*

**

***

****

*****

但我得到了这个。


*

**

***

****

*****

*****

最后一行 star 似乎有重复,我不知道为什么会这样。你能帮助我吗?


这是我的代码:


public class Test1 {


    public static void main(String[] args) {


        for (int i = 1; i <= 5; i++) {

            System.out.println("*");

            for (int j = 1; j <= i; j++) {

                System.out.print("*");

            }

        }

    }

}


慕的地10843
浏览 125回答 4
4回答

慕村225694

你把换行符放在错误的位置。我会把它与写作分开*,比如public class Test1 {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i <= 5; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = 1; j <= i; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

素胚勾勒不出你

*你一开始就打印一个。它应该像你正在做的那样完成。在 1 次完整迭代后打印新行For,如下所示:代码:for (int i = 1; i <= 5; i++)&nbsp;{&nbsp; &nbsp; //System.out.println("*");&nbsp; &nbsp;// This line should not be here&nbsp;&nbsp; &nbsp; for (int j = 1; j <= i; j++)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; // you can print new line after each nested-for compleletion}

宝慕林4294392

简短回答(TL;DR)你的换行符放错了。在内部 for 循环执行之后放置换行符,如下所示:public class Test1 {public static void main(String[] args) {&nbsp; &nbsp; for (int i = 1; i <= 5; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 1; j <= i; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; }}详细解答首先,您必须了解System.out.print()和之间的区别System.out.println()。这两个基本上做同样的事情:他们打印出传递给他们的参数。但是,有一个明显的区别:System.out.println()在打印后生成一个新的换行符,但System.out.print实际上并没有。要理解这个概念,请检查下面的示例代码:System.out.println("Tadaa");System.out.print("Ta");System.out.print("daa");System.out.print("Stackoverflow");其输出将是:多田多田堆栈溢出使用这个逻辑,很容易看出哪里出了问题。直觉上,中断 [ .println()] 应该发生在每次迭代结束时。我希望这有帮助。编码愉快!

幕布斯6054654

这是所需输出的代码for (int i = 1; i <= 5; i++)&nbsp;{&nbsp; &nbsp; //System.out.println("*");&nbsp; &nbsp;&nbsp; &nbsp; for (int j = 1; j <= i; j++)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("*");&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java