我是一名編程初學者,所以我很抱歉如果這是一個簡單的問題。我的程序在啓動應用程序時會產生一個隨機數學問題(另外)。用戶輸入他/她認爲的答案。接下來,用戶點擊按鈕並顯示文本,指示用戶的回答是否正確。我可以在C#中使用兩個不同事件的相同局部變量嗎?
我在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();
}
}
}
啊是的!謝謝philologon!我很高興你今天教會了我一些新的東西:) – Learnin2Code
無論你認爲哪一個答案是最重要的,你應該通過點擊左邊選票按鈕下的「接受答案」圖標來「接受」答案。在問題至少10分鐘之前,您無法做到這一點。 – philologon
噢,好的,對不起,我不知道。我正在尋找一種「關閉」問題的方法。謝謝 – Learnin2Code