我是一个编程初学者,如果这是一个简单的问题,我很抱歉。我的程序在启动应用程序时生成一个随机的数学问题(加法)。用户输入他/她认为的答案。接下来,用户点击按钮,显示的文本指示用户的答案是否正确。
我在Form Load事件中使用了变量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();
}
}
}