[英]How do I create a multiple if statement in VB.NET?
所以我試圖通過將表達式推入堆棧來制作一個中綴來反轉波蘭符號程序。 該程序迭代表達式以查找運算符,一旦找到它,它就會彈出 2 個值並執行計算。 但是,如果我嘗試添加多個 if 語句,則會彈出轉換錯誤。 “if express(i) <> “+” 行用於添加但是如果我要通過添加多個條件來擴展它“if express(i) <> “+” or “-” or “*” 然后它說“從字符串“-”轉換為類型 Boolean 無效。 誰能幫我解決這個問題? 謝謝。
模塊模塊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
端模塊
每次比較時,您應該 state 左表達式,例如
if express(i) <> "+" or express(i) <> "-" or express(i) <> "*"
試試這個
Module Module1
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 tempVal As Integer
For i = 0 To expres.Length - 1
If Array.IndexOf({"+", "-", "*", "/", "^", "~"}, expres(i)) = -1 Then
s.Push(expres(i))
End If
current(0) = s.Pop().ToString
current(1) = s.Pop().ToString
Select Case expres(i)
Case "+"
tempVal = current(0) + current(1)
Case "-"
tempVal = current(0) - current(1)
Case "*"
tempVal = current(0) * current(1)
Case "/"
tempVal = current(0) / current(1)
Case "^"
tempVal = current(0) ^ current(1)
Case "~"
tempVal = current(0) + current(1)
End Select
Console.WriteLine(tempVal)
s.Push(tempVal)
Next
Console.ReadLine()
End Sub
End Module
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.