-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
尝试逐步调试并查看代码正在执行的操作。 –