user2275554
user2275554

Reputation: 23

Functions in Visual Basic

I'm supposed to make a score calculator for a Programming assignment, for a football game. it has 4 textboxes and a button, the function NEEDS to be there for full credit, I'm just not sure what I'm doing wrong.

Public Class Form1
Dim intTotal = 0
Dim intFirst = 0
Dim intSecond = 0
Dim intThird = 0
Dim intFourth = 0
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Try
        Dim intFirst As Integer = Convert.ToInt32(txtFirst.Text)
        Dim intSecond As Integer = Convert.ToInt32(txtSecond.Text)
        Dim intThird As Integer = Convert.ToInt32(txtThird.Text)
        Dim intFourth As Integer = Convert.ToInt32(txtFourth.Text)
    Catch ex As Exception
        MessageBox.Show("Enter in Digits!")
    End Try
    intTotal = calcTotal(intFirst, intSecond, intThird, intFourth, intTotal)
    Me.lblTotal.Text = intTotal 'Shows as 0 at run-time
End Sub
Function calcTotal(ByVal intFirst As Integer, ByVal intSecond As Integer, ByVal intThird As Integer, ByVal intFourth As Integer, ByVal intTotal As Integer) As Integer
    intTotal = intFirst + intSecond + intThird + intFourth
    Return intTotal
End Function
End Class

lblTotal ends up displaying 0.

Upvotes: 1

Views: 401

Answers (2)

Kenneth
Kenneth

Reputation: 28747

Your variables are declared at the block-level inside the try catch. Move the declarations out of the block and remove the class-level declarations (since they're not necesarry).

Like this:

Public Class Form1
    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

        Dim intFirst As Integer = 0
        Dim intSecond As Integer = 0
        Dim intThird As Integer = 0
        Dim intFourth As Integer = 0

        Try
           intFirst = Convert.ToInt32(txtFirst.Text)
            intSecond = Convert.ToInt32(txtSecond.Text)
            intThird = Convert.ToInt32(txtThird.Text)
            intFourth = Convert.ToInt32(txtFourth.Text)
        Catch ex As Exception
            MessageBox.Show("Enter in Digits!")
        End Try
        Dim intTotal as Integer = calcTotal(intFirst, intSecond, intThird, intFourth, intTotal)
        Me.lblTotal.Text = intTotal 'Shows as 0 at run-time
    End Sub

    Function calcTotal(ByVal intFirst As Integer, ByVal intSecond As Integer, ByVal intThird As Integer, ByVal intFourth As Integer, ByVal intTotal As Integer) As Integer
        Return intFirst + intSecond + intThird + intFourth
    End Function
End Class

Upvotes: 2

Komlan
Komlan

Reputation: 102

I am not sure what your problem is but your variable declaration are outside of your function . You should initialize them inside.

Upvotes: 0

Related Questions