2017-12-25 5 views
0

は、私は左側にスペースを残すことができますどのようにこの表示逆さピラミッド

5 4 3 2 1 2 3 4 5 
    4 3 2 1 2 3 4 
    3 2 1 2 3 
     2 1 2 
     1 

のような出力を持つようにしたいですか?

public class Exercise4_17 { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter the number of lines: "); 
     int num = input.nextInt(); 
     Exercise4_17 exe = new Exercise4_17(); 
     exe.displayPyramid(num); 
    } 

    private void displayPyramid(int num) { 

     for (int i = num; i >= 1; i--) { 
      for (int space = 1; space <= num - i; ++space) { 
       System.out.print(" "); 
      } 
      for (int k = num; k >= 1; k--) { 
       System.out.print(k + " "); 
      } 

      for (int j = 2; j <= num; j++) { 
       System.out.print(j + " "); 
      } 
      System.out.println(); 
      num--; 
     } 
    } 
} 

マイ出力

Enter the number of lines: 5 
5 4 3 2 1 2 3 4 5 
4 3 2 1 2 3 4 
3 2 1 2 3 
2 1 2 
1 
+0

あなたのスペース印刷ループが実際にスペースを印刷していない理由を把握するためにデバッガを使用することです。 – einpoklum

答えて

2

あなたのコードは非常に近いです。まず、スタイルの問題として、私は2番目のループのために同じ変数名を使用します(jは厄介です、ちょうどkを使用してください)。第二に、実際の問題は、numあなたのループを変更しています。ループの前にの初期値を保存して、スペース計算に使用してください。同様に、

final int initial = num; // <-- add this 
for (int i = num; i >= 1; i--) { 
    for (int space = 1; space <= initial - i; ++space) { // <-- use initial instead of num 
     System.out.print(" "); 
    } 
    for (int k = num; k >= 1; k--) { 
     System.out.print(k + " "); 
    } 
    for (int k = 2; k <= num; k++) { // <-- j should still work of course... 
     System.out.print(k + " "); 
    } 
    System.out.println(); 
    num--; 
} 
+0

愚かな間違い!ありがとう。 –

1

希望します。

import java.util.Scanner; 
public class MainClass { 
    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     //Taking noOfRows value from the user 
     System.out.println("How Many Rows You Want In Your Pyramid?"); 
     int noOfRows = sc.nextInt(); 
     //Initializing rowCount with noOfRows 
     int rowCount = noOfRows; 
     System.out.println("Here Is Your Pyramid"); 
     //Implementing the logic 
     for (int i = 0; i < noOfRows; i++) { 
      //Printing i*2 spaces at the beginning of each row 
      for (int j = 1; j <= i*2; j++) { 
       System.out.print(" "); 
      } 
      //Printing j where j value will be from 1 to rowCount 
      for (int j = rowCount; j >= 1; j--) { 
       System.out.print(j+" "); 
      } 
      //Printing j where j value will be from rowCount-1 to 1 
      for (int j = 2; j <= rowCount; j++) { 
        System.out.print(j+" "); 
      } 
      System.out.println(); 
      //Decrementing the rowCount 
      rowCount--; 
     } 
    } 
} 

REF link

出力:あなたがあなたのピラミッドにしたい行数 ? は、ここであなたのピラミッド

5 4 3 2 1 2 3 4 5 

    4 3 2 1 2 3 4 

    3 2 1 2 3 

     2 1 2 

     1 
関連する問題