-3
我們必須爲校園製作基於GUI的程序。我們基本上必須創建一個基於2人戰鬥的遊戲,用戶必須輸入他們的統計數據和這些數據被用於戰鬥。沒有其他用戶輸入。我設法完成它,但是當我運行該程序時,我收到此錯誤:我該如何解決這個錯誤:索引超出了數組的範圍
未處理的異常發生在您的應用程序中。如果您單擊 繼續應用程序將忽略此錯誤並嘗試繼續。 如果單擊退出該應用程序將立即關閉 指數數組的邊界之外
我的代碼:
public Form1()
{
InitializeComponent();
}
//Declaring Jaggered Array
string[][] playerstat = new string[2][];
private void button1_Click(object sender, EventArgs e)
{
//Retrieving information from textboxes for player 1
string name1 = txtName1.Text;
string htpt1 = txtHtPt1.Text;
string attack1 = txtAttack1.Text;
string def1 = txtDef1.Text;
//Assigning Player1 Values
playerstat[0] = new string[4] { name1, htpt1, attack1, def1 };
}
private void panel4_Paint(object sender, PaintEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
//Retrieving information from textboxes for player 2
string name2 = txtName2.Text;
string htpt2 = txtHtPt2.Text;
string attack2 = txtAttack2.Text;
string def2 = txtDef2.Text;
//Assigning Player2 Values
playerstat[1] = new string[4] { name2, htpt2, attack2, def2 };
}
private void btnFight_Click(object sender, EventArgs e)
{
string p1name = playerstat[0][1];
string sp1hp = playerstat[0][2];
int p1hp = Int32.Parse(sp1hp);
string sp1a = playerstat[0][3];
int p1a = Int32.Parse(sp1a);
string sp1d = playerstat[0][4];
int p1d = Int32.Parse(sp1d);
string p2name = playerstat[1][1];
string sp2hp = playerstat[1][2];
int p2hp = Int32.Parse(sp1hp);
string sp2a = playerstat[1][3];
int p2a = Int32.Parse(sp1a);
string sp2d = playerstat[1][4];
int p2d = Int32.Parse(sp1d);
//Fighting Loop
while(!(p1hp == 0) || !(p2hp == 0))
{
p2hp = p1a - (p2hp + p2d);
txtFOP.Text = p1name + " deals " + p1a + " damage to " + p2name + " who now has " + p2hp;
p1hp = p2a - (p1hp + p1d);
txtFOP.Text = p2name + " deals " + p2a + " damage to " + p1name + " who now has " + p1hp;
}
}
}
}
您的陣列的所述第二部分的每個索引嘗試創建一個[MCVE];你很可能會發現問題。如果你不想這樣做,在調試器中運行你的代碼。你也可以參考[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –
數組是基於0的索引。 'playerstat [0] [4];'當只有4時嘗試訪問第5個位置。 – Equalsk
嘗試逐步調試並查看代碼正在執行的操作。 –