【问题标题】:Error in C# random addition programC#随机加法程序出错
【发布时间】:2016-01-16 20:15:45
【问题描述】:

我在声明 int userIN = int.Parse(answerBox.Text); 的行上不断收到错误消息。我不明白为什么会这样。我确信这只是我忽略的东西,但我一直坐在这里完全困惑。

“System.FormatException”类型的未处理异常发生在 mscorlib.dll

附加信息:输入字符串的格式不正确。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RandomAddition
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // First Random Nummber
            int rand1;
            Random rn1 = new Random();
            rand1 = rn1.Next(500) + 100;
            number1.Text = rand1.ToString();
            //Second Random Number
            int rand2;
            rand2 = rn1.Next(500) + 100;
            number2.Text = rand2.ToString();
            // Answer
            int anw = rand1 + rand2;
            int answ = rand1 + rand2;
            // Check
            int userIN = int.Parse(answerBox.Text);
            if (answ == userIN)
            {
                feedback.Text = "Correct";
            }
            else
            {
                feedback.Text = "incorrect";
            }
        }
    }
}

【问题讨论】:

  • “我不断收到错误” .... 错误说明了什么?
  • 究竟是什么错误? answerBox.Text 的值是多少,你的 CurrentCulture 是多少?调试您的代码并告诉我们。
  • 在 mscorlib.dll 中出现“System.FormatException”类型的未处理异常附加信息:输入字符串的格式不正确。
  • @TacosaurusRex:那么显然输入字符串的格式不正确。输入字符串是什么?

标签: c# math random addition


【解决方案1】:

使用int.TryParse 而不是int.Parse 更改您的//Check 部分:

// Check
int userIN;
if(int.TryParse(answerBox.Text, out userIN))
{
    if (answ == userIN)
    {
        feedback.Text = "Correct";
    }
    else
    {
        feedback.Text = "incorrect";
    }
}
else
{
    feedback.Text = "incorrect";
}

这样,当您的表单仍然为空时,您可以避免 FormatException。

干杯

【讨论】:

    【解决方案2】:

    如果您尝试将空字符串(answerBox.Text 可能为空)解析为整数,则会出现 FormatException,请确保文本框包含有效值。

    【讨论】:

      【解决方案3】:

      看起来你正在构建一个猜谜游戏。

      您正在尝试parse answerBox 中的文本,但由于表单刚刚加载,因此可以安全地假定它为空。

      将空字符串解析为int 将引发异常。

      这部分代码只应在响应用户按下按钮等事件时引发。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多