【问题标题】:Format Exception was unhandled...?格式异常未处理...?
【发布时间】: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


【解决方案1】:

让我们看看:

 for (...) {
   ...
   students[counter].personGPA = Convert.ToDouble(txtGPA.Text);
   ...
   txtGPA.Text = string.Empty;

你已经解析txtGPA.Text然后清除它并尝试再次解析(因为代码在for循环)。 empty 值无法转换为 double 并且您会抛出异常。

您可能想要循环中的所有值:

 double gpa = Convert.ToDouble(txtGPA.Text); 
 txtGPA.Text = String.Empty;

 for (...) {
   ... 
   students[counter].personGPA = gpa;

请注意,students[counter] 仍然是非常可疑的代码,因为counter 不是循环变量(即i)。

【讨论】:

  • 自行完成 for 循环(在 new student(); 之后结束)并清除 try catch 之外的文本框修复了它 - 谢谢大家的帮助!
猜你喜欢
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
相关资源
最近更新 更多