我的老师为我提供了用于创建程序的代码,但是,当我运行它时,它给了我'FormatException未处理'。它建议我将字符串转换为DateTime,但这与代码无关。我真的无法确定问题所在。我正在使用C#,通过Microsoft Visual Studio,如果有任何帮助的话。
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; }
}
}
答案 0 :(得分:0)
我们来看看:
for (...) {
...
students[counter].personGPA = Convert.ToDouble(txtGPA.Text);
...
txtGPA.Text = string.Empty;
您解析 txtGPA.Text
然后清除并尝试再次解析(因为代码在 for loop )。 empty 值无法转换为double
,您将抛出异常。
可能你想拉循环中的所有值:
double gpa = Convert.ToDouble(txtGPA.Text);
txtGPA.Text = String.Empty;
for (...) {
...
students[counter].personGPA = gpa;
请注意,students[counter]
仍然是非常可疑的代码,因为counter
不是循环变量(即i
)。