测试运营商。错误转换为double? (计算器应用)

时间:2013-10-29 20:50:47

标签: vb.net

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

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

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.

我尝试将字符串更改为double并将文本框转换为double,但我仍然得到相同的错误。我只是宣布错了吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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