我奉命創建使用嵌套循環和二維數組,並一直在努力了幾天乘法表乘法表時。該表有3個功能:加載陣列,顯示陣列和搜索陣列。我對循環沒有經驗,但我認爲我完成了這部分。然而,雖然沒有顯示錯誤,當我調試/運行該程序時,「負荷陣列」按鈕不執行任何操作,將「顯示陣列」按鈕顯示9號在頂部,然後一個「超出範圍」異常出現;當我點擊「搜索陣列」,它只能當我輸入一個「0」 ......這應該是搜索輸入作爲文本框中的搜索標準數量的所有出現的數組。我認爲加上一個try-catch塊可能會有幫助,但不知道如何解決等問題...問題加載,顯示和搜索使用嵌套循環和二維數組
這裏是我的代碼:
namespace CS12c
{
public partial class frmCS12c : Form
{
int [ , ] intTable = new int[9,9]; // 9 x 9 table
public frmCS12c()
{
InitializeComponent();
}
private void btnLoadArray_Click(object sender, EventArgs e)
{
int r; //row
int c; //column
int intResult; //result
//Index references begin at zero
for (r = 0; r < intTable.GetLength(0); r++) //Use intTable.GetLength(0) and intTable.GetLength(1) to control processing
{
for (c = 0; c < intTable.GetLength(1); c++) //Add 1 to the indexes before multiplying to build multiplication table
{
intResult = (r + 1) * (c + 1);
intTable[r, c] = intResult;
}
txtTable.AppendText("\r\n");
}
}
//Modify the nested for loops used above to nested while loops
private void btnDisplayArray_Click(object sender, EventArgs e)
{
int r; //row
int c; //column
string strSpace;
txtTable.Clear(); //clear the text box
for (r = 0; r < 9; r++)
{
for (c = 0; c < 9; r++)
{
if (intTable[r, c] < 10)
strSpace = " "; //two spaces
else
strSpace = " "; //one space
txtTable.AppendText(strSpace); // insert space
txtTable.AppendText(intTable[r, c].ToString()); //insert result
}
txtTable.AppendText("\r\n"); //Move down one line
}
}
private void btnSearchArray_Click(object sender, EventArgs e)
{
int r; //row
int c; //column
int intSearchNumber; //Search number
txtTable.Clear(); //clear the text box
//Not enclosed in a try-catch; make you enter a number in textbox
intSearchNumber = int.Parse(txtSearchNumber.Text);
//In search display all occurences that match the search numbers
for (r = 0; r < intTable.GetLength(0); r++)
{
for (c = 0; c < intTable.GetLength(1); c++)
{
if (intSearchNumber == intTable[r, c])
txtTable.AppendText(intTable[r, c].ToString() + " is located in " + r + ", " + c);
}
txtTable.AppendText("\r\n");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}//end of form
}//end of namespace
任何人誰可以幫助將真正成爲一個生命的保護程序,謝謝...
你是什麼意思,負載「什麼都不做」。你期待它做什麼?它填充數組並附加一些換行符。 –
添加'嘗試{/ *你的代碼中btnSearchArray_Click這裏* /}趕上(例外){MessageBox.Show(的String.Format( 「R:{0},C:{1}」,r.ToString(),C .ToString()))}' –
@ Pau808如果添加'Try ... Catch ...',你可以知道你在哪個索引錯誤。 –