2014-01-10 41 views
0

我一直在研究一個問題,現在要在控制檯中繪製一個鑽石,要求用戶輸入,然後根據輸入的尺寸繪製鑽石。控制檯中的鑽石繪圖

我不能在這裏畫鑽石,因爲格式不能正確顯示。

我已經能夠成功地獲得鑽石的上半部分的工作,我認爲下半部分會很容易,因爲它只是頂部的反面,但是我卡在某些東西上,而我不能似乎弄明白了。

這裏是我的代碼:

import java.util.Scanner; 

public class Diamond { 

    public static void main(String[] args) { 

     // import the scanner 
     Scanner scanner = new Scanner(System.in); 

     // Ask for the number of sides 
     System.out.println("Enter the diamond size: "); 
     int sides = scanner.nextInt(); 

     //variables for the diamond 
     int matrix = sides * 2 + 3; 
     int midpoint = ((matrix - 1)/2) + 1; 
     int mspaces = 0; 
     int centerSpaces = 0; 


     // diamond gets made here 
     for (int rows = 1; rows <= midpoint; rows++) { 
      int spaces = (sides * 2 + 2) - (sides + rows); 
      if (rows == 1) { 
       for (int x = 1; x <= spaces; x++) { 
        System.out.print(" "); 
       } 
       System.out.print("^\n"); 
      } 

      //top half of the diamond 
      if (rows > 1 && rows < midpoint) { 

       if (rows > 2) { 
        mspaces += 2; 
       } 

       for (int x = 1; x <= spaces; x++) { 
        System.out.print(" "); 
       } 
       System.out.print("/"); 

       for (int k = 0; k <= mspaces; k++) { 
        System.out.print(" "); 
       } 

       System.out.print("\\\n"); 

       centerSpaces = mspaces + 2; 

      } 

      //center of the diamond 
      if (rows == midpoint) { 
       System.out.print("<"); 
       for (int i = 0; i <= centerSpaces; i++) { 
        System.out.print(" "); 
       } 
       System.out.print(">"); 
      } 
     } 

     //Bottom half of the diamond 
     for (int x = midpoint - 1; x <= 1; x--) { 

      int downSpace = (sides * 2 + 2) - (sides + x); 

      System.out.println("\n"); 

      if (x == 1) { 
       for (int y = 1; y <= downSpace; y++) { 
        System.out.println(" "); 
       } 

       if (x > 2) { 
        mspaces += 2; 
       } 

       for (int y = 1; x <= downSpace; y++) { 
        System.out.print(" "); 
       } 
       System.out.print("\\"); 

       for (int k = 0; k <= mspaces; k++) { 
        System.out.print(" "); 
       } 

       System.out.print("/\n"); 

       centerSpaces = mspaces + 2; 

      } 
     } 

    } 
} 

如果我不得不採取猜測它是什麼,它會是什麼東西在if聲明對鑽石的下半部分,但我不完全當然。

編輯:

這是鑽石的上半部分的截圖:

enter image description here

+0

你能粘貼不正確的結果是什麼樣子嗎? – turbo

+0

@turbo我已經添加了上半部分的屏幕截圖,現在的問題是沒有在下半部分打印出來... – 23k

+0

而不是發佈屏幕截圖,最好是發佈實際輸出。你知道如何從命令行復制文本嗎?你使用什麼操作系統? –

回答

1

循環永遠不會運行:應閱讀x>=1(我認爲)

for (int x = midpoint - 1; x <= 1; x--) 

可能無限循環:應讀取y <= downSpace

for (int y = 1; x <= downSpace; y++) 
+0

比這兩個還有更多的錯誤。例如,有一個'System.out.println(「」);'應該是'System.out.print'。還有其他人。 OP只需要逐一處理這些小問題。 –

+0

@DavidWallace修復了所有你注意到的事件,以及所有人都在使用,但仍有一些事情,但至少我在底部發生了一些事情 – 23k

+1

是的,我知道還有其他人。我最初發現了與ns47731相同的兩個。我不會花我的時間來調查和打印所有問題。但我認爲你現在可以看到足夠的鑽石能夠爲自己解決問題。你只需要堅持下去。 –