Passaggio 4: aggiungere il metodo CheckTheAnswer()

Nella quarta parte di questa esercitazione si scriverà un metodo, CheckTheAnswer(), che verifica se le risposte ai problemi di matematica sono corrette.Questo argomento fa parte di una serie di esercitazioni sui concetti di codifica di base.Per una panoramica dell'esercitazione, vedere Esercitazione 2: creare un quiz matematico a tempo

[!NOTA]

Se si utilizza Visual Basic, poiché questo metodo restituisce un valore, anziché la solita parola chiave Sub si utilizzerà invece la parola chiave Function.È molto semplice: una subroutine non restituisce un valore, ma una funzione sì.

Per verificare se le risposte sono corrette

  1. Aggiungere il metodo CheckTheAnswer().

    Quando viene chiamato, questo metodo aggiunge i valori di addend1 e addend2 e confronta il risultato al valore nel controllo NumericUpDown della somma.Se i valori sono uguali, il metodo restituisce il valore true.In caso contrario, il metodo restituisce il valore false.Il codice dovrebbe essere analogo al seguente.

    ''' <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
    
    /// <summary> 
    /// Check the answer 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)
            return true;
        else 
            return false;
    }
    

    Successivamente, si controllerà la risposta aggiornando il codice nel metodo per il gestore dell'evento Tick del timer per chiamare il nuovo metodo CheckTheAnswer().

  2. Aggiungere il codice seguente all'istruzione if else:

    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
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (CheckTheAnswer())
        {
            // 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 the answers right!",
                            "Congratulations!");
            startButton.Enabled = true;
        }
        else if (timeLeft > 0)
        {
           // 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--;
            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;
        }
    }
    

    Se la risposta è corretta, CheckTheAnswer() restituisce true.Il gestore eventi arresta il timer, visualizza un messaggio di congratulazioni e rende quindi nuovamente disponibile il pulsante Avvio.In caso contrario, il quiz continua.

  3. Salvare il programma, eseguirlo, avviare un quiz e fornire una risposta corretta al problema di addizione.

    [!NOTA]

    Prima di immettere la risposta è necessario selezionare il valore predefinito oppure eliminare manualmente lo zero.Si correggerà questo comportamento più avanti in questa esercitazione.

    Quando si fornisce una risposta corretta, viene aperta una finestra di messaggio, il pulsante Avvio diventa disponibile e il timer si arresta.

Per continuare o rivedere l'esercitazione