猿问

java - 如何在java中使用三个嵌套的for循环来实现带有_的倒金字塔?

我在试图弄清楚如何使用扫描仪创建具有三个嵌套 for 循环的金字塔时遇到了麻烦。


我必须做到这一点


Enter a number

6

1 2 3 4 5 6 


- 1 2 3 4 5 


- - 1 2 3 4


- - - 1 2 3


- - - - 1 2


- - - - - 1

我基本上已经尝试过了,我知道这是错误的,但我知道我必须做什么,但我不知道该怎么写。


Scanner ent= new Scanner(System.in);

System.out.println("Enter a number");

int x= ent.nextInt();



for(int a = x; a >= 1; a--) {

    for(int c=1;c<=x;c++) {

        System.out.print("_");

        for(int b = 1; b <= a; b++) { 

            System.out.print(d + " "); 

        } 

    }

    System.out.println("");

}


慕尼黑8549860
浏览 134回答 2
2回答

烙印99

把这个图案一分为二。短跑从 1 到 n 的数字首先计算你需要打印多少次这个图案。这里6次。&nbsp; &nbsp; int n=in.nextInt();&nbsp; &nbsp; for(int i=1;i<=n;i++)&nbsp; &nbsp; {&nbsp; &nbsp; }每次您需要打印破折号后跟数字。短跑------------Row | Dashes------------&nbsp;1&nbsp; |&nbsp; 0&nbsp;2&nbsp; |&nbsp; 1&nbsp;3&nbsp; |&nbsp; 2&nbsp;4&nbsp; |&nbsp; 3&nbsp;5&nbsp; |&nbsp; 4&nbsp;6&nbsp; |&nbsp; 5所以我引入了一个变量 dashes=0 并增加每一行的破折号。&nbsp; &nbsp; int n=in.nextInt();&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; int dashes=0;&nbsp; &nbsp; for(int i=1;i<=n;i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for(int j=1; j<=dashes;j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("-");&nbsp; &nbsp; &nbsp; &nbsp; dashes++;&nbsp; &nbsp; }数字从 1 开始,以 (n-i+1) 结尾------------Row | Numbers (n-i+1)------------&nbsp;1&nbsp; |&nbsp; 123456&nbsp;&nbsp;2&nbsp; |&nbsp; 12345&nbsp;3&nbsp; |&nbsp; 1234&nbsp;4&nbsp; |&nbsp; 123&nbsp;5&nbsp; |&nbsp; 12&nbsp;6&nbsp; |&nbsp; 1所以最终的代码是&nbsp; &nbsp; int n=in.nextInt();&nbsp; &nbsp; int dashes=0;&nbsp; &nbsp; for(int i=1;i<=n;i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for(int j=1; j<=dashes;j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("-");&nbsp; &nbsp; &nbsp; &nbsp; for(int k=1;k<=n-i+1;k++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(k);&nbsp; &nbsp; &nbsp; &nbsp; // for next row - starts in new line&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; dashes++;&nbsp; &nbsp; }

慕少森

这是一种方法:System.out.println("Enter a number");int x = ent.nextInt();for (int i=0; i < x; ++i) {&nbsp; &nbsp; for (int j=0; j < i; ++j) System.out.print("- ");&nbsp; &nbsp; for (int j=1; j <= (x-i); ++j) {&nbsp; &nbsp; &nbsp; &nbsp; if (j > 1) System.out.print(" ");&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(j);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}1 2 3 4 5 6- 1 2 3 4 5- - 1 2 3 4- - - 1 2 3- - - - 1 2- - - - - 1逻辑是使用两个单独的内部循环,一个用于破折号,它首先出现,另一个用于数字。破折号的循环从 0 运行到i-1,即外循环之前的一个位置。然后,对于该行的其余部分,我们打印从 1 到 的数字x - i。
随时随地看视频慕课网APP

相关分类

Java
我要回答