2011-10-25 91 views
3

我想用Java寫一個捕捉用戶整數(假設數據有效)的程序,然後根據整數的大小輸出菱形形狀,即用戶輸入5,輸出將是:使用循環的Java ascii藝術

--*-- 
-*-*- 
*---* 
-*-*- 
--*-- 

到目前爲止,我有:

if (sqr < 0) { 
     // Negative 
     System.out.print("#Sides of square must be positive"); 
    } 

    if (sqr % 2 == 0) { 
     // Even 
     System.out.print("#Size (" + sqr + ") invalid must be odd"); 
    } else { 
     // Odd 
     h = (sqr - 1)/2; // Calculates the halfway point of the square 
     // System.out.println(); 
     for (j=0;j<sqr;j++) {  

      for (i=0;i<sqr;i++) { 

       if (i != h) { 
        System.out.print(x); 
       } else { 
        System.out.print(y); 
       } 

      } 

      System.out.println(); 
     } 

    } 

剛剛輸出

--*-- 
--*-- 
--*-- 
--*-- 
--*-- 

任何ID eas,我在考慮減少h的價值,但那隻會產生鑽石的左手邊。

回答

2
void Draw(int sqr) 
     { 
      int half = sqr/2; 
      for (int row=0; row<sqr; row++) 
      { 
       for (int column=0; column<sqr; column++) 
       { 
        if ((column == Math.abs(row - half)) 
         || (column == (row + half)) 
         || (column == (sqr - row + half - 1))) 
        { 
         System.out.print("*"); 
        } 
        else 
        { 
         System.out.print("_"); 
        } 
       } 
       System.out.println(); 
      } 
     } 

好吧,現在這是代碼,但正如我看到S.L. Barth的評論我剛剛意識到這是一項家庭作業。因此,我強烈建議您在將其作爲最終使用之前理解此代碼中編寫的內容。隨意問任何問題!

+0

您能否向我解釋一下Math.abs()函數的作用,我是否認爲它給出了任何數字的正值?我已經向您的代碼添加了評論,以表明我明白髮生了什麼。 – Mike

+1

你說得對,邁克,這正是它所做的。 –

2

在你的情況請看下圖:

if (i != h) 

這僅着眼於列數(i)和中間點(H)。 您需要查看列號和行號的條件。更確切地說,您需要一個條件來查看列號,行號和中間點列號的距離。
由於這是一個家庭作業問題,所以我給你確定了精確的公式,但是如果你需要,我願意放棄一些更多的提示。祝你好運!

+0

另外,想想第一行和最後一行是其他行的特例(只有1 * iso 2) – gastush

+0

@ gastush不一定。如果條件由兩部分組成,則只有其中一個需要評估爲「真」,以便打印*。 –