2011-11-03 25 views
0

我正在寫一個程序,我需要製作一個空心的asterixs盒子。當我輸入一個正方形的尺寸時,程序工作正常,但當我輸入一個矩形的尺寸時它不起作用。爲什麼程序輸出正確,如果尺寸創建一個正方形而不是矩形?

import java.util.Scanner; 
public class asterix { 
    public static void main(String[] args) { 

    Scanner input = new Scanner(System.in); 

int stars; // length of side 
int column; // width of box 
int row = 1; 

// prompt user to enter the length and width of box 

System.out.print("Enter the length: "); 
stars = input.nextInt(); 

System.out.print("Enter the width: "); 
column = input.nextInt(); 



while (row <= stars) { 
    column = 1; 

// and for as many columns as rows 
while (column <= stars) { 

    if (row == 1) 
    System.out.print("*"); 

    else if (row == stars) 
    System.out.print("*"); 

    else if (column == 1) 
    System.out.print("*"); 

    else if (column == stars) 
    System.out.print("*"); 

    else 
    System.out.print(" "); 

column++; } // end inner while loop 

System.out.println(); 
row++; 


     } // end output 
    } // end of main 
} // end of Stars 

理想的輸出我想如下:

說,它的3×3:

 
    *** 
    * * 
    *** 

,並說,它的4 3:

 
    **** 
    * * 
    **** 
+0

這是一個家庭作業嗎? – ewok

+0

感謝編輯 –

+0

沒有它的個人改進 –

回答

2

您需要修改以下幾行。

System.out.print("Enter the width: "); 
int numberOfColumns = input.nextInt(); 

while (column <= numberOfColumns) 

你兩個循環比較的行數,並因此得到一個正方形。您應該使用內循環中的列數。

我敢肯定,這只是一個滑倒,你會抓住它。

+0

感謝很多隊友,現在的作品! –

+0

沒問題,很樂意幫忙。 –

2

columnrow代表你當前座標(看到,因爲他們是修改在環)。

在開始時您讀取的用戶輸入爲starscolumn,所以這些應該代表的最大值的數字。

正如您注意到的那樣,有一些重疊。您需要將column定義爲或者當前位置的最大列數,並定義一個新的變量的其他含義。

這表明具有意義的名稱是多麼重要,即使它們更長。如果您已經指定了變量maxColumns,maxRowscurrentColumncurrentRow,那麼問題可能是非常可見

相關問題