2

我正在编写一个小型数学游戏,其中生成总和,当回答时,得分,然后生成另一个总和。大约一个小时前,该程序完美无缺,但原因之一是;如果用户尝试输入包含多个数字的任何内容(除了将 - 放在数字之前,用于负值),程序将崩溃。这是我当前用于解析输入的代码(我可能使用了错误的术语;如果是这样,我很抱歉):

private void txtAnswer_KeyPress(object sender, KeyPressEventArgs e)
    {
        // If a press of the enter key is detected... 
        if(e.KeyChar == (char)Keys.Return)
        {
            // The player's answer is converted to an integer and checked against the correct answer. 
            userguess = System.Convert.ToInt32(txtAnswer.Text);

            if (userguess == answer)
            {
                // If the player's answer is correct, an appropriate message is displayed and 1 point added to the kill-score. 
                lblResult.Text = "# Enemy charge calculated correctly, charge bounced back and damage evaded.";
                lblRight.Text = (System.Convert.ToInt32(lblRight.Text) + 1).ToString();
            }
            else
            {
                // If the player's answer is incorrect, an appropriate message is displayed and 100 points are added to the damages cost counter. 
                lblResult.Text = "# Enemy charge calculated incorrectly, charge fired and hit! The charge had " + answer.ToString() + " power units applied.";
                lblWrong.Text = (System.Convert.ToInt32(lblWrong.Text) + 100).ToString();
            }
            // After appropriate action has been taken based on the player's answer, a new sum is generated. 
            makeNewSum();
        }
    }

我不是那么先进的编码器,我不知道如何让它在允许它通过之前检查实际提交的内容,如果它不好则崩溃。谁能帮我吗?

4

2 回答 2

2

那是因为一个字符例如不能转换为Int32,改变这个:

userguess = System.Convert.ToInt32(txtAnswer.Text);

对此:

if (!int.TryParse(txtAnswer.Text, out userguess)) { return; }

如果成功,则将整数值设置为,userguess以便程序的其余部分可以保持不变。

于 2013-09-09T16:48:05.277 回答
2

尝试这样的事情:

int userguess;
if (int.TryParse(txtAnswer.Text, out userguess))
{
        if (userguess == answer)
        {
            // If the player's answer is correct, an appropriate message is displayed and 1 point added to the kill-score. 
            lblResult.Text = "# Enemy charge calculated correctly, charge bounced back and damage evaded.";
            lblRight.Text = (System.Convert.ToInt32(lblRight.Text) + 1).ToString();
        }
        else
        {
            // If the player's answer is incorrect, an appropriate message is displayed and 100 points are added to the damages cost counter. 
            lblResult.Text = "# Enemy charge calculated incorrectly, charge fired and hit! The charge had " + answer.ToString() + " power units applied.";
            lblWrong.Text = (System.Convert.ToInt32(lblWrong.Text) + 100).ToString();
        }
        // After appropriate action has been taken based on the player's answer, a new sum is generated. 
        makeNewSum();               
}
else{
    lblResult.Text = "Incorrect value!";
}

TryParse将尝试解析您的文本值并将结果放入用户猜测中。如果成功则返回true,如果失败则返回false。

于 2013-09-09T16:48:18.690 回答