Step 4: Add the CheckTheAnswer() Method
In the fourth part of this tutorial, you'll write a method,
CheckTheAnswer(), that determines whether the answers to the math problems are correct. This topic is part of a tutorial series about basic coding concepts. For an overview of the tutorial, see Tutorial 2: Create a Timed Math Quiz.
If you're following along in Visual Basic, you'll use the
When this method is called, it adds the values of addend1 and addend2 and compares the result to the value in the sum
NumericUpDowncontrol. If the values are equal, the method returns a value of
true. Otherwise, the method returns a value of
false. Your code should look like the following.
''' <summary> ''' Check the answer to see if the user got everything right. ''' </summary> ''' <returns>True if the answer's correct, false otherwise.</returns> ''' <remarks></remarks> Public Function CheckTheAnswer() As Boolean If addend1 + addend2 = sum.Value Then Return True Else Return False End If End Function
Next, you'll check the answer by updating the code in the method for the timer's Tick event handler to call the new
Add the following code to the
Private Sub Timer1_Tick() Handles Timer1.Tick If CheckTheAnswer() Then ' If CheckTheAnswer() returns true, then the user ' got the answer right. Stop the timer ' and show a MessageBox. Timer1.Stop() MessageBox.Show("You got all of the answers right!", "Congratulations!") startButton.Enabled = True ElseIf timeLeft > 0 Then ' If CheckTheAnswer() return false, keep counting ' down. Decrease the time left by one second and ' display the new time left by updating the ' Time Left label. timeLeft -= 1 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 End If End Sub
If the answer is correct,
true. The event handler stops the timer, shows a congratulatory message, and then makes the Start button available again. Otherwise, the quiz continues.
Save your program, run it, start a quiz, and provide a correct answer to the addition problem.
When you enter your answer, you must either select the default value before you start to enter your answer, or you must delete the zero manually. You'll correct this behavior later in this tutorial.
When you provide a correct answer, a message box opens, the Start button becomes available, and the timer stops.
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.