亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

java - 如何在java中使用三個嵌套的for循環來實現帶有_的倒金字塔?

java - 如何在java中使用三個嵌套的for循環來實現帶有_的倒金字塔?

慕尼黑8549860 2022-10-12 15:28:02
我在試圖弄清楚如何使用掃描儀創建具有三個嵌套 for 循環的金字塔時遇到了麻煩。我必須做到這一點Enter a number61 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("");}
查看完整描述

2 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

把這個圖案一分為二。

  1. 短跑

  2. 從 1 到 n 的數字

首先計算你需要打印多少次這個圖案。這里6次。

    int n=in.nextInt();

    for(int i=1;i<=n;i++)

    {


    }

每次您需要打印破折號后跟數字。


短跑


------------

Row | Dashes

------------

 1  |  0

 2  |  1

 3  |  2

 4  |  3

 5  |  4

 6  |  5

所以我引入了一個變量 dashes=0 并增加每一行的破折號。


    int n=in.nextInt();     

    int dashes=0;


    for(int i=1;i<=n;i++)

    {

        for(int j=1; j<=dashes;j++)

            System.out.print("-");

        dashes++;

    }

數字從 1 開始,以 (n-i+1) 結尾


------------

Row | Numbers (n-i+1)

------------

 1  |  123456 

 2  |  12345

 3  |  1234

 4  |  123

 5  |  12

 6  |  1

所以最終的代碼是


    int n=in.nextInt();


    int dashes=0;


    for(int i=1;i<=n;i++)

    {

        for(int j=1; j<=dashes;j++)

            System.out.print("-");


        for(int k=1;k<=n-i+1;k++)

            System.out.print(k);


        // for next row - starts in new line

        System.out.println();

        dashes++;

    }


查看完整回答
反對 回復 2022-10-12
?
慕少森

TA貢獻2019條經驗 獲得超9個贊

這是一種方法:


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

int x = ent.nextInt();


for (int i=0; i < x; ++i) {

    for (int j=0; j < i; ++j) System.out.print("- ");

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

        if (j > 1) System.out.print(" ");

        System.out.print(j);

    }

    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。


查看完整回答
反對 回復 2022-10-12
  • 2 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號