【发布时间】:2016-04-12 12:41:40
【问题描述】:
我的老师为我提供了用于创建程序的代码,但是,当我运行它时,它给了我“FormatException was unhandled”。它建议我将字符串转换为 DateTime,但这与代码无关。我真的无法确定问题出在哪里。如果有帮助的话,我正在通过 Microsoft Visual Studio 使用 C#。
private void btnAdd_Click(object sender, EventArgs e)
{
student[] students = new student[5];
int i;
for (i = 0; i < 5; i++)
{
students[i] = new student();
try
{
int counter = 0; //array index counter
students[counter].personName = txtName.Text;
students[counter].personGPA = Convert.ToDouble(txtGPA.Text);
txtDisplay.Text += "Name: " + students[counter].Name + "\r\n GPA: " + students[counter].GPA.ToString();
counter++; //increment the array index counter by 1
txtName.Text = string.Empty;
txtGPA.Text = string.Empty;
txtName.Focus();
} //end of code for the try block
catch (ArgumentException) //GPA is out of range
{
MessageBox.Show("Please enter a proper GPA");
}
catch (IndexOutOfRangeException) //array is full
{
MessageBox.Show("There are already 5 students.");
}
}
}
class student
{
public String personName;
public Double personGPA;
public string Name
{
// get;
//set;
get { return personName; }
set { personName = value; }
}
public double GPA
{
//get;
//set;
get {return personGPA; }
set { personGPA = value; }
}
}
【问题讨论】:
-
具体发生在哪一行
-
我怀疑它实际上在
Convert.ToDouble(txtGPA.Text)失败了...txtGPA.Text的值是多少? -
是的,但请举例说明您输入的失败文本
-
@Naima 你能在那儿放一个断点并检查值吗?
2绝对不会失败。 -
@Naima 仔细一看,这是因为您正在执行循环(5 次),但您在第一次迭代后清除了文本。
txtGPA.Text = string.Empty;。如果没有完全删除,这些清除应该在循环之外。
标签: c# arrays class counter formatexception