2015-11-06 102 views
0

我試圖使輸出是這樣的:反平行四邊形

enter image description here

我知道問題出在第三圈,但我不知道怎樣做才能彌補這方面的工作空間。

import java.util.Scanner; 

public class Tester { 

    public static void main(String[] args){ 

     Scanner in = new Scanner(System.in); 
     int x, y; 
     System.out.print("Enter the number of rows: "); 
     x = in.nextInt(); 
     System.out.print("Enter the number of stars: "); 
     y = in.nextInt(); 

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

      //loop for y stars 
      for(int j = 0; j < y; j++){ 
       System.out.print("* "); 
      } 

      System.out.println(); 

      for(int l = 0; l <= i; l--){ 
       System.out.print(" "); 
      } 
     } 
    } 
} 
+1

輸出什麼,你現在得到些什麼? –

+0

我目前收到這個http://prntscr.com/8zjv4s – Roland

回答

0

你需要做幾件事情。

第一個是將您的最後一個嵌套for循環(打印空格的循環)移動到第一個循環的開始位置。您還需要刪除已添加到打印星號的for循環的空間。

然後,對於您向我們展示的輸出結果,您需要在最後開始主循環,並向後退出。

嘗試以下操作:

public static void main (String[] args) { 
    Scanner in = new Scanner(System.in); 
    System.out.print("Enter the number of rows: "); 
    int x = in.nextInt(); 
    System.out.print("Enter the number of stars: "); 
    int y = in.nextInt(); 

    //loop for x lines 
    //This starts at x and goes toward 0 
    for(int i = x; i > 0; i--){ 
     //Insert spaces based on line number 
     //This is at the beginning now 
     for (int s = 0; s < i; s++) 
      System.out.print(" "); 

     //Print y stars 
     //Removed the space after the asterisk 
     for(int j = 0; j < y; j++) 
      System.out.print("*"); 

     System.out.println(); 
    } 
} 

測試here和輸出在第一圖像相匹配

0

您必須重新訂購for循環。請注意,在條件在第二個for循環中給出頌以下變化:

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

     for(int l = 0; l <= x-i; ++l){ 
      System.out.print(" "); 
     } 

     //loop for y stars 
     for(int j = 0; j < y; j++){ 
      System.out.print("* "); 
     } 

     System.out.println(); 


    } 
0
for (int i = 0; i < x; i++){ 
     for (int j = x-1; j > i; j--) { 
      System.out.print(" "); 
     } 
     for(int j = 0; j < y; j++){ 
      System.out.print("*"); 
     } 
      System.out.println(); 
    } 
+0

請考慮添加一些解釋,以便OP瞭解您的解決方案爲什麼會起作用 –

0

另一種方式:

String stars = String.format("%0" + y + "d", 0).replace('0', '*'); 
    for (int i=x; i > 0; i--) 
    { 
     System.out.println(String.format("%0$"+i+ "s", ' ')+stars); 
    } 
    System.out.println(stars);