我是编程初学者,所以如果这是一个简单的问题,我很抱歉。我的程序在启动应用程序时会生成一个随机数学问题(另外)。用户输入他/她认为是答案的内容。接下来,用户点击一个按钮并显示文本,指示用户的答案是否正确。
我在表单加载事件中使用了变量 number1 和 number2。如何在按钮单击事件中轻松再次使用它们?
(希望我的代码演示了我正在尝试做的事情).....
public Form1()
{
InitializeComponent();
}
//New Method
private void GenerateRandoms()
{
// create random number variable
Random randomNumber = new Random();
int number1;
int number2;
number1 = randomNumber.Next(100, 501);
number2 = randomNumber.Next(100, 501);
randomProblemLeft.Text = number1.ToString();
randomProblemRight.Text = number2.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
// Call created method so random numbers are generated once form loads.
GenerateRandoms();
}
private void checkButton_Click(object sender, EventArgs e)
{
int rightAnswer; //The correct answer for the addition problem
int theirAnswer; // The answer given by the user
theirAnswer = int.Parse(answerInput.Text);
rightAnswer = (number1 + number2); //Trying to reuse these variables from first event????????????
if (rightAnswer == theirAnswer)
{
checkOutput.Text = "Yes, that is the correct answer!";
}
else
{
checkOutput.Text = "Sorry, that is incorrect!";
}
}
private void clearButton_Click(object sender, EventArgs e)
{
answerInput.Text = "";
checkOutput.Text = "";
GenerateRandoms();
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}