我寫了兩個類。主類運行程序。它要求用戶輸入。基於用戶輸入,第二類將打印出一個正方形。每個方格都會打印出來----每個數字和|爲牆壁的每個數字。修復了基於用戶輸入增長的方塊
例如,假設用戶輸入了兩個。在這種情況下,它會打印出一個正方形。
----- -----
| |
| |
----- -----
問題是我不能根據用戶輸入獲得正方形的增長。
這是主類
import java.util.Scanner;
public class Assignment4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
SquareBuilder square = new SquareBuilder(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
square.changeSize(scan.nextInt());
System.out.print(square.toString());
}
}
public class SquareBuilder
{
final private int LENGTH_RATIO = 4;
final private String CEILING_FLOOR = "----";
private int size;
private int spaces;
private String square;
public SquareBuilder(int size)
{
this.size = size;
constructSquare();
}
private void spaces()
{
spaces = LENGTH_RATIO * size - 2;
}
private void ceilingAndFloor()
{
square += "\n";
for (int i = 0; i < size; ++i)
{
square += CEILING_FLOOR;
}
}
private void walls()
{
for (int i = 0; i < size; ++i)
{
square +="\n|";
for (int j = 0; j < spaces; ++j)
{
square +=" ";
}
square +="|";
}
}
private void constructSquare()
{
spaces();
square = "";
ceilingAndFloor();
walls();
ceilingAndFloor();
}
public int area()
{
return size * size;
}
public void changeSize(int size)
{
this.size = size;
}
public String toString()
{
String retVal = square;
retVal += "\nSize: " + size + " Area: " + area();
return retVal;
}
}
什麼是錯誤? – mbeckish 2013-05-01 17:53:26
正方形應該根據用戶輸入增長。基本的方形打印----底部和頂部天花板和|爲牆壁。如果他們輸入了兩個,它會打印出來---- ----和| |對於每一面牆 ----- ----- – user2340248 2013-05-01 18:01:12
你確定,我只是複製並粘貼它,它運行良好。 – 2013-05-01 18:05:05