2016-07-16 44 views
0

我想打印字符的三角形。我想要這樣。在java中打印字符的三角形

     A 
        A B 
        A B C 
        A B C D 
        A B C D E 

以下是我的代碼。

public class Pro8Point3 
{ 
    public static void main(String[] args){ 
    int space=29; 
    char ch; 
    for (int i=1; i<=5; i++) { 
     ch='A'; 
     //Print spaces in decreasing order. A is at 29th position. 
     for (int j=1; j<=space; j++) { 
     System.out.println(" "); 
     } 
     //Print Triangle. 

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

但它不給我慾望輸出。請指導我在這裏犯了什麼錯誤。

+1

如果您還發布了當前的輸出,會更容易。 – johnnyaug

回答

2
System.out.println(" "); 

應該

System.out.print(" "); 

,你應該去掉這一行的for循環的底部:

System.out.println(); 

最終代碼,搞掂格式化並提出了上述變化:

public class Pro8Point3 
{ 
    public static void main(String[] args) { 
     int space=29; 
     char ch; 

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

      //Print spaces in decreasing order. A is at 29th position. 
      for (int j = 1; j <= space; j++) { 
       System.out.print(" "); 
      } 

      //Print Triangle. 
      for (int k = 1; k <= i; k++) { 
       System.out.print(ch + " "); 
       ch+=1; 
      } 

      space--; 

      System.out.println(); 
     } 
    } 
} 

輸出:

       A 
          A B 
          A B C 
          A B C D 
         A B C D E 
+0

是的。非常感謝。它的工作現在。謝謝。 –

2

@ smarx的正確答案後,我想發佈一個通用的方法來滿足這樣的要求。它可能看起來像這樣

public class Pro8Point3 { 

    public static void main(String[] args) { 
     print(5, 20); 
    } 

    private static void print(int level, int position) { 

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

      char c = 'A'; 

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

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

      System.out.println(); 

     } 
    } 
}