1

我应该为足球比赛的编程作业制作分数计算器。它有 4 个文本框和一个按钮,该功能需要有完整的信用,我只是不确定我做错了什么。

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。

4

2 回答 2

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
于 2013-04-18T21:05:40.460 回答
0

我不确定你的问题是什么,但你的变量声明在你的函数之外。你应该在里面初始化它们。

于 2013-04-18T21:01:23.400 回答