当使用函数VB.Net

时间:2018-06-01 21:15:04

标签: vb.net visual-studio visual-studio-2010 visual-studio-2012

当a / b中b等于0时,我试图返回false,以便我的错误消息显示给用户。到目前为止,我已经设法在我的sub中进行检查,但我需要检查是否在函数内。目前,我得到一个无穷大的结果,例如7除以0.我基本上做了一个非常基本的计算器,并希望得到任何帮助。

功能:

Private Function validationCheck() As Boolean
    ' The following checks if the two fields are numerical values, are not blank and if the 2nd number is not zero
    'The latter is for the purpose of division
    'If the fields meet the above conditions then true is returned
    'Else if either one is not met, then false is returned
    If IsNumeric(txt1stNumber.Text) And txt1stNumber.Text <> "" And IsNumeric(txt2ndNumber.Text) And txt2ndNumber.Text <> "" Then
        Return True
    Else
        Return False
    End If
End Function

Division Sub

 Private Sub btnDivide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDivide.Click

    'The following sub is the code for the division button.
    'First it checks whether false is returned from the ValidationCheck funtion
    'If so, an error message is shown
    'Else if true is returned, then the values are divided together to form the result

    If validationCheck() = False Then
        MsgBox("Please enter a numerical value for both fields. Also, field cannot be left blank.")
    ElseIf validationCheck() = True Then
        lblResult.Text = Val(txt1stNumber.Text) / Val(txt2ndNumber.Text)
    End If

1 个答案:

答案 0 :(得分:-1)

你可以在你的函数中再添加一个条件来评估txt2ndNumber.Text,然后如果数字b是0或00,那么这也将返回false。

  Private Function validationCheck() As Boolean
     If IsNumeric(txt1stNumber.Text) And txt1stNumber.Text <> "" And IsNumeric(txt2ndNumber.Text) And txt2ndNumber.Text <> "" Then
        Dim number As Double = txt2ndNumber.Text
        If number = 0 Then
            Return False
        Else
            Return True
        End If
     Else
       Return False
     End If
  End Function