2013-04-18 81 views
1

我應該爲編程任務做一個分數計算器,用於足球比賽。 它有4個文本框和一個按鈕,函數需要在那裏充分的信用,我只是不知道我在做什麼錯了。Visual Basic中的函數

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最終顯示爲0。

+0

這有什麼錯呢? –

+0

lblTotal結束顯示0 – user2275554

回答

2

您的變量在try catch內的塊級聲明。將聲明移出塊並刪除類級聲明(因爲它們不是必需的)。

像這樣:

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 
+0

謝謝,這工作! – user2275554

+0

沒問題。請記住要提供幫助並接受其中一個答案的答案。 – Kenneth

0

我不知道你的問題是什麼,但你的變量聲明爲你的函數之外。你應該在裏面初始化它們。

+0

謝謝,這工作,但不是在函數中聲明,我在事件過程中聲明,在函數中聲明提出了一整套新問題。 – user2275554