Megosztás a következőn keresztül:


Step 6: Add a Subtraction Problem

In the sixth part of this tutorial, you'll add a subtraction problem and learn how to perform the following tasks:

  • Store the subtraction values.

  • Generate random numbers for the problem (and be sure that the answer is between 0 and 100).

  • Update the method that checks the answers so that it checks the new subtraction problem too.

  • Update your timer's Tick event handler so that the event handler fills in the correct answer when time runs out.

To add a subtraction problem

  1. Add two integer variables for the subtraction problem to your form, between the integer variables for the addition problem and the timer. The code should look like the following.

    Public Class Form1
    
        ' Create a Random object called randomizer  
        ' to generate random numbers. 
        Private randomizer As New Random
    
        ' These integer variables store the numbers  
        ' for the addition problem.  
        Private addend1 As Integer 
        Private addend2 As Integer 
    
        ' These integer variables store the numbers  
        ' for the subtraction problem.  
        Private minuend As Integer 
        Private subtrahend As Integer 
    
        ' This integer variable keeps track of the  
        ' remaining time. 
        Private timeLeft As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object called randomizer  
        // to generate random numbers.
        Random randomizer = new Random();
    
        // These integer variables store the numbers  
        // for the addition problem.  
        int addend1;
        int addend2;
    
        // These integer variables store the numbers  
        // for the subtraction problem.  
        int minuend;
        int subtrahend;
    
        // This integer variable keeps track of the  
        // remaining time. 
        int timeLeft;
    

    The names of the new integer variables—minuend and subtrahend—aren't programming terms. They're the traditional names in arithmetic for the number that's being subtracted (the subtrahend) and the number from which the subtrahend is being subtracted (the minuend). The difference is the minuend minus the subtrahend. You could use other names, because your program doesn't require specific names for variables, controls, components, or methods. You must follow rules such as not starting names with digits, but you can generally use names such as x1, x2, x3, and x4. However, generic names make code difficult to read and problems nearly impossible to track down. To keep variable names unique and helpful, you'll use the traditional names for multiplication (multiplicand × multiplier = product) and division (dividend ÷ divisor = quotient) later in this tutorial.

    Next, you'll modify the StartTheQuiz() method to provide random values for the subtraction problem.

  2. Add the following code after the "Fill in the subtraction problem" comment.

    ''' <summary> 
    ''' Start the quiz by filling in all of the problem  
    ''' values and starting the timer.  
    ''' </summary> 
    ''' <remarks></remarks> 
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem. 
        ' Generate two random numbers to add. 
        ' Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
    
        ' Convert the two randomly generated numbers 
        ' into strings so that they can be displayed 
        ' in the label controls.
        plusLeftLabel.Text = addend1.ToString()
        plusRightLabel.Text = addend2.ToString()
    
        ' 'sum' is the name of the NumericUpDown control. 
        ' This step makes sure its value is zero before 
        ' adding any values to it.
        sum.Value = 0
    
        ' Fill in the subtraction problem.
        minuend = randomizer.Next(1, 101)
        subtrahend = randomizer.Next(1, minuend)
        minusLeftLabel.Text = minuend.ToString()
        minusRightLabel.Text = subtrahend.ToString()
        difference.Value = 0
    
        ' Start the timer.
        timeLeft = 30
        timeLabel.Text = "30 seconds"
        Timer1.Start()
    
    End Sub
    
    /// <summary> 
    /// Start the quiz by filling in all of the problem  
    /// values and starting the timer.  
    /// </summary> 
    public void StartTheQuiz()
    {
        // Fill in the addition problem. 
        // Generate two random numbers to add. 
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers 
        // into strings so that they can be displayed 
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
        // 'sum' is the name of the NumericUpDown control. 
        // This step makes sure its value is zero before 
        // adding any values to it.
        sum.Value = 0;
    
        // Fill in the subtraction problem.
        minuend = randomizer.Next(1, 101);
        subtrahend = randomizer.Next(1, minuend);
        minusLeftLabel.Text = minuend.ToString();
        minusRightLabel.Text = subtrahend.ToString();
        difference.Value = 0;
    
        // Start the timer.
        timeLeft = 30;
        timeLabel.Text = "30 seconds"; 
        timer1.Start();
    }
    

    To prevent negative answers for the subtraction problem, this code uses the Next() method of the Random class a little differently from how the addition problem does. When you give the Next() method two values, it picks a random number that's greater than or equal to the first value and less than the second one. The following code chooses a random number from 1 through 100 and stores it in the minuend variable.

    minuend = randomizer.Next(1, 101)
    
    minuend = randomizer.Next(1, 101);
    

    You can call the Next() method of the Random class, which you named "randomizer" earlier in this tutorial, in multiple ways. Methods that you can call in more than one way are referred to as overloaded, and you can use IntelliSense to explore them. Look again at the tooltip of the IntelliSense window for the Next() method.

    Intellisense window tooltip

    Intellisense window tooltip

    The tooltip shows (+ 2 overload(s)), which means that you can call the Next() method in two other ways. Overloads contain different numbers or types of arguments, so that they work slightly differently from one another. For example, a method might take a single integer argument, whereas one of its overloads might take an integer and a string. You choose the correct overload based on what you want it to do. When you add the code to the StartTheQuiz() method, more information appears in the Intellisense window as soon as you enter randomizer.Next(. Choose the Up Arrow and Down Arrow keys to cycle through the overloads, as the following illustration shows.

    Overload for Next() method in IntelliSense

    Overload for Next() method in IntelliSense

    In this case, you want to choose the last overload, because you can specify minimum and maximum values.

  3. Modify the CheckTheAnswer() method to check for the correct subtraction answer.

    ''' <summary> 
    ''' Check the answers 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 AndAlso 
           minuend - subtrahend = difference.Value Then 
    
            Return True 
        Else 
            Return False 
        End If 
    
    End Function
    
    /// <summary> 
    /// Check the answers to see if the user got everything right. 
    /// </summary> 
    /// <returns>True if the answer's correct, false otherwise.</returns> 
    private bool CheckTheAnswer()
    {
        if ((addend1 + addend2 == sum.Value)
            && (minuend - subtrahend == difference.Value))
            return true;
        else 
            return false;
    }
    

    In Visual C#, && is the logical and operator. In Visual Basic, the equivalent operator is AndAlso. These operators indicate "If the sum of addend1 and addend2 equals the value of the sum NumericUpDown and if minuend minus subtrahend equals the value of the difference NumericUpDown." The CheckTheAnswer() method returns true only if the answers to the addition and the subtraction problems are both correct.

  4. Replace the last part of the timer's Tick event handler with the following code so that it fills in the correct answer when time runs out.

    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
        difference.Value = minuend - subtrahend
        startButton.Enabled = True 
    End If
    
    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;
        difference.Value = minuend - subtrahend;
        startButton.Enabled = true;
    }
    
  5. Save and run your code.

    Your program includes a subtraction problem, as the following illustration shows.

    Math quiz with subtraction problem

    Math quiz with subtraction problem

To continue or review