カテゴリー
Visual Basic

Visual Basicで逆ポーランド記法の式を作る。()無し

Imports System

Module Program
    Class elem
        Public ope As String
        Public lev As Integer
    End Class
    Sub Main(args As String())
        Dim inpstr As String = "6.1 + 5.2 * 4.3 - 3.4 / 2.5 * 1.6 "
        Dim rpnstr As String = ""
        Dim opeStack As New Stack
        Dim aelem As New elem

        While True
            If inpstr.Length = 0 Then
                GoTo owari
            End If

            Dim fSpacePosition As Integer = inpstr.IndexOf(" ")
            Dim fstr As String = inpstr.Substring(0, fSpacePosition)
            Dim nstr As String = Strings.Right(inpstr, inpstr.Length - fSpacePosition - 1)

            If Not (fstr = "+" Or fstr = "-" Or fstr = "*" Or fstr = "/") Then
                '演算子以外の数値は出力する
                rpnstr += fstr + " "

            Else
                If opeStack.Count >= 1 Then
                    Dim wope As elem = opeStack.Peek
                    Dim currentlev As Integer

                    Select Case fstr
                        Case "*" : currentlev = 2
                        Case "/" : currentlev = 2
                        Case "+" : currentlev = 1
                        Case "-" : currentlev = 1
                        Case Else : currentlev = 0
                    End Select

                    Do While wope.lev >= currentlev And opeStack.Count >= 1
                        rpnstr += wope.ope + " "
                        opeStack.Pop()
                        If opeStack.Count > 0 Then
                            wope = opeStack.Peek
                        End If
                    Loop

                    Dim belem As New elem
                    belem.ope = fstr
                    belem.lev = currentlev
                    opeStack.Push(belem)

                Else
                    '最初のスタックへの積上げ
                    If fstr = "+" Or fstr = "-" Then
                        aelem.lev = 1
                    Else
                        aelem.lev = 2
                    End If
                    aelem.ope = fstr
                    opeStack.Push(aelem)
                End If

            End If
            inpstr = nstr
        End While
owari:
        Dim welem As elem
        Do While opeStack.Count > 0
            welem = opeStack.Pop
            rpnstr += welem.ope + " "
        Loop
        Console.WriteLine(rpnstr)
        Console.WriteLine("Hello World!")
    End Sub
End Module

コメントを残す

メールアドレスが公開されることはありません。

inserted by FC2 system