Step 4: Add the CheckTheAnswer() Method
Your quiz needs to verify whether the user answers correctly. Fortunately, writing methods that do a simple calculation, such as the CheckTheAnswer() method, isn't difficult.
Note
|
|---|
|
For those who are following along in Visual Basic, it's worth noting that because this method returns a value, instead of the usual Sub keyword, you'll be using the Function keyword instead. It's really that simple: Subs don't return a value, but functions do. |
To add the CheckTheAnswer() method
-
Add the CheckTheAnswer() method, which adds addend1 and addend2 and verifies whether the sum is equal to the value in the sum NumericUpDown control. If the sum is equal, the method returns true; if not, it returns false. Your code should look like the following.
Your program needs to call this method to verify whether the user answered correctly. You do this by adding to your if else statement. The statement looks like the following.
-
Next, you modify the timer's Tick event handler to check the answer. The new event handler with answer checking should include the following.
private void timer1_Tick(object sender, EventArgs e) { if (CheckTheAnswer()) { // If the user got the answer right, stop the timer // and show a MessageBox. timer1.Stop(); MessageBox.Show("You got all the answers right!", "Congratulations"); startButton.Enabled = true; } else if (timeLeft > 0) { // Decrease the time left by one second and display // the new time left by updating the Time Left label. timeLeft--; timeLabel.Text = timeLeft + " seconds"; } else { // If the user ran out of time, stop the timer, show // a MessageBox, and fill in the answers. timer1.Stop(); timeLabel.Text = "Time's up!"; MessageBox.Show("You didn't finish in time.", "Sorry"); sum.Value = addend1 + addend2; startButton.Enabled = true; } }
Now if the timer's event handler finds that the user answered correctly, the event handler stops the timer, shows a congratulations message, and makes the Start button available again.
-
Save and run your program. Start the game, and type the correct answer to the addition problem.
Note
When you type your answer, you may notice something odd about the NumericUpDown control. If you start typing without selecting the entire answer, the zero remains, and you must delete it manually. You will correct this later in this tutorial.
-
When you type the correct answer, the message box should open, the Start button should be available, and the timer should stop. Click the Start button again and be sure this happens.
To continue or review
-
To go to the next tutorial step, see Step 5: Add Enter Event Handlers for the NumericUpDown Controls.
-
To return to the previous tutorial step, see Step 3: Add a Countdown Timer.