下面是改進命名和頂線圖(順便說一句,你有你的代碼不正確的行顯示 - 你是在第二循環迭代行列代替):
const int columnWidth = 5;
string cellFormat = "{0, " + columnWidth + "}";
Console.Write("How wide do we want the multiplication table? ");
int columnsCount = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int rowsCount = Convert.ToInt32(Console.ReadLine());
string title = String.Format(cellFormat + "|", "x");
Console.Write(title);
for (int i = 1; i <= columnsCount; i++)
Console.Write(cellFormat, i);
Console.WriteLine();
int tableWidth = columnWidth * columnsCount + title.Length;
Console.WriteLine(new String('-', tableWidth));
for (int row = 1; row <= rowsCount; row++)
{
Console.Write(cellFormat + "|", row);
for (int column = 1; column <= columnsCount; column++)
Console.Write(cellFormat, row * column);
Console.WriteLine();
}
的Nex t重構步驟是提取類和方法:
Console.Write("How wide do we want the multiplication table? ");
int columnsCount = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int rowsCount = Convert.ToInt32(Console.ReadLine());
MultiplicationTable table = new MultiplicationTable(columnsCount, rowsCount);
table.Draw();
現在代碼更清晰 - 它告訴你有乘法表,並且你想繪製它。繪畫很簡單 - 你畫列標題和原糖:
public class MultiplicationTable
{
private const int columnWidth = 5;
private string cellFormat = "{0, " + columnWidth + "}";
private int columnsCount;
private int rowsCount;
public MultiplicationTable(int columnsCount, int rowsCount)
{
this.columnsCount = columnsCount;
this.rowsCount = rowsCount;
}
public void Draw()
{
DrawColumnHeaders();
DrawRaws();
}
private void DrawColumnHeaders()
{
string title = String.Format(cellFormat + "|", "x");
Console.Write(title);
for (int i = 1; i <= columnsCount; i++)
Console.Write(cellFormat, i);
Console.WriteLine();
int tableWidth = columnWidth * columnsCount + title.Length;
Console.WriteLine(new String('-', tableWidth));
}
private void DrawRaws()
{
for (int rowIndex = 1; rowIndex <= rowsCount; rowIndex++)
DrawRaw(rowIndex);
}
private void DrawRaw(int rowIndex)
{
DrawRawHeader(rowIndex);
for (int columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
DrawCell(rowIndex * columnIndex);
Console.WriteLine();
}
private void DrawRawHeader(int rowIndex)
{
Console.Write(cellFormat + "|", rowIndex);
}
private void DrawCell(int value)
{
Console.Write(cellFormat, value);
}
}
感謝。這肯定有幫助。它並沒有完全得到我想要的,但是在第一個for語句中,我添加了〜for(int i = 1; i <= width + 1; i ++);〜並且得到了它。再次感謝!!! – user1707042