C#随机添加程序出错

时间:2015-10-18 13:02:59

标签: c# math random addition

我一直在行中声明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";
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

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

您正在尝试parse answerBox内的文字,但由于表单刚刚加载,因此可以安全地假设它是空的。

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

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

答案 1 :(得分:1)

使用//Check代替int.TryParse更改您的int.Parse部分:

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

这样,当Form仍然为空时,您可以避免使用FormatException。

干杯

答案 2 :(得分:0)

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

相关问题