【问题标题】:How do I create a multiple if statement in VB.NET?如何在 VB.NET 中创建多重 if 语句?
【发布时间】:2019-10-17 08:35:22
【问题描述】:

所以我试图通过将表达式推入堆栈来制作一个反转波兰符号程序的中缀。该程序迭代表达式以查找运算符,一旦找到它,它就会弹出 2 个值并执行计算。但是,如果我尝试添加多个 if 语句,则会弹出转换错误。 “if express(i) “+” 行用于添加但是如果我要通过添加多个条件来扩展它“if express(i) “+” or “-” or “*” 然后它说“从字符串“-”转换为布尔类型无效。谁能帮我解决这个问题?谢谢。

模块模块1

Sub Main()
    Dim expres As String
    Console.WriteLine("Enter infix expression")
    expres = Console.ReadLine()
    Dim S As New Stack
    Dim current(1) As Integer
    Dim temp_val As Integer
    For i = 0 To expres.Length - 1
        If expres(i) <> "+" Then
            S.Push(expres(i))
        End If

        If expres(i) = "+" Then
            current(0) = S.Pop().ToString
            current(1) = S.Pop().ToString
            temp_val = current(0) + current(1)
            Console.WriteLine(temp_val)
            S.Push(temp_val)

        End If
        If expres(i) = "-" Then
            current(0) = S.Pop().ToString
            current(1) = S.Pop().ToString
            temp_val = current(0) - current(1)
            Console.WriteLine(temp_val)
            S.Push(temp_val)

        End If
        If expres(i) = "*" Then
            current(0) = S.Pop().ToString
            current(1) = S.Pop().ToString
            temp_val = current(0) * current(1)
            Console.WriteLine(temp_val)
            S.Push(temp_val)

        End If
        If expres(i) = "/" Then
            current(0) = S.Pop().ToString
            current(1) = S.Pop().ToString
            temp_val = current(0) / current(1)
            Console.WriteLine(temp_val)
            S.Push(temp_val)

        End If
        If expres(i) = "^" Then
            current(0) = S.Pop().ToString
            current(1) = S.Pop().ToString
            temp_val = current(0) ^ current(1)
            Console.WriteLine(temp_val)
            S.Push(temp_val)

        End If
        If expres(i) = "~" Then
            current(0) = S.Pop().ToString
            current(1) = S.Pop().ToString
            temp_val = current(0) + current(1)
            Console.WriteLine(temp_val)
            S.Push(temp_val)

        End If
    Next
    Console.ReadLine()
End Sub

结束模块

【问题讨论】:

  • 能详细解释一下if express(i) &lt;&gt; "+" or "-" or "*"的预期逻辑吗?
  • 改用 Select 语句。现在它只是变成了 Case Else 子句。

标签: vb.net


【解决方案1】:

你应该在每次比较时说明左边的表达式,比如

if express(i) &lt;&gt; "+" or express(i) &lt;&gt; "-" or express(i) &lt;&gt; "*"

【讨论】:

  • @freefaller “花括号”通常指的是大括号。我看没有大括号。您指的是智能引号(MS office 称它们为)?
  • @Mary,是的,打字太快了,没有注意到我的错误……你完全正确……我的意思是花括号
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 2022-01-14
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多