0

所以我只是在做这个基本的计算器事情,试图学习更多的VB。我有这个应用程序有 3 个文本框,用户输入 2 个值(每个框中 1 个),然后在第三个框中输入一个运算符(+、-、*、/)

我在这里有一个方法可以检查用户是否输入了运算符:

Private Function isOperator(ByVal textBox As TextBox, ByVal name As String)
    Dim strOperatorList As String() = {"+", "-", "/", "*"}
    If Not strOperatorList.Contains(textBox.Text) Then
        MessageBox.Show(name & " does not contain a valid operator.", "Entry Error")
        textBox.SelectAll()
        Return False
    Else
        Return True
    End If
End Function

我很确定这是有效的。我的按钮单击时出现错误:

Try
        If IsValidData() Then
            Dim operand1 As Decimal = CDec(txtOperand1.Text)
            Dim operand2 As Decimal = CDec(txtOperand2.Text)
            Dim strOperator As Double = CDbl(txtOperator.Text)
            Dim result As Decimal = operand1 + strOperator + operand2

            txtResult.Text = result
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message & vbCrLf & vbCrLf &
                        ex.GetType.ToString & vbCrLf & vbCrLf &
                        ex.StackTrace, "Exception")
    End Try

错误在行:

Dim strOperator As string = txtOperator.Text

错误说:

Conversion from string "+" to type Double is not valid.

我尝试将字符串更改为双精度并将文本框转换为双精度,但仍然出现相同的错误。我只是宣布它错了吗?

4

2 回答 2

1

您不能将运算符转换为数字,请使用字符串:

Dim operator As String = txtOperator.Text

然后,您不能将字符串用作运算符,因为字符串是数据,而运算符是代码的一部分。从操作员那里确定如何处理这些值:

Dim result As Decimal
If operator = "+" Then
  result = operand1 + operand2
ElseIf operstor = "-" Then
  result = operand1 - operand2
ElseIf operator = "/" Then
  result = operand1 / operand2
ElseIf operator = "*" Then
  result = operand1 * operand2
Else
  ' Oops, unknown opreator
End If
于 2013-10-29T20:58:55.823 回答
0
Try
    If IsValidData() Then
        Dim operand1 As Decimal = CDec(txtOperand1.Text)
        Dim operand2 As Decimal = CDec(txtOperand2.Text)
        Dim strOperator As String = txtOperator.Text
        Dim result as Decimal
        Select Case strOperator
           Case "+"
              result = operand1 + operand2                  
           Case "-"
              result = operand1 - operand2                 
           Case "*"
              result = operand1 * operand2                  
           Case "/"
              result = operand1 / operand2
           Case Else
              'error
        end Select                 

        txtResult.Text = result
    End If
Catch ex As Exception
    MessageBox.Show(ex.Message & vbCrLf & vbCrLf &
                    ex.GetType.ToString & vbCrLf & vbCrLf &
                    ex.StackTrace, "Exception")
End Try
于 2013-10-29T21:01:38.187 回答