유효 그것을 할 수있는 더 많은 방법, 그리고 나는 +/-의 구문 분석에 대해 100 % 만족하지는 않지만, 속임수를 쓰면 텍스트를 구문 분석하는 방법에 대한 아이디어를 얻을 수 있습니다.)문제가 해결되지 않을 경우 참고,이 클래스의 유일한 해결 방법이며, 전체 과도 구현은,이 방법은/오류가 발생, 그래서 중 하나 시도 내에서이 방법을 묶어야합니다
아래에 다음과 Catch 블록 또는 아래 찾을 수 있습니다 :)
이 Public Overrides Sub Resolve(input As String)
' lets say 2x^2 + 4x - 4 = 0
' lets say 5x^2 + 3x + 1 = 0
If String.IsNullOrWhiteSpace(input) Then
Throw New ArgumentException("Input string cannot be null", "input")
End If
If input.IndexOf("=") >= 0 Then
input = input.Split("=")(0).Trim()
If String.IsNullOrWhiteSpace(input) Then
Throw New FormatException("'=' is at the beginning of the equation")
End If
End If
If input.Contains(" ") Then
input = input.Replace(" ", "")
End If
Dim lstGroup As New List(Of String)
Dim position As Integer = 0
Dim delimiters() As String = {"+", "-"}
Dim minIndex As Integer
Dim curDel As String
Dim lastDel As String = "+"
Dim part As String
While position < input.Length
minIndex = input.Length
curDel = "+"
For Each del In delimiters
Dim targetIndex As Integer = input.IndexOf(del, position)
If targetIndex > 0 AndAlso targetIndex < minIndex Then
minIndex = targetIndex
curDel = del
End If
Next
part = input.Substring(position, minIndex - position)
lstGroup.Add(lastDel + part.ToLower())
position = minIndex + 1
lastDel = curDel
End While
CoefficientA = 0
CoefficientB = 0
CoefficientC = 0
For Each group In lstGroup
If group.Contains("x^2") Then
If CoefficientA <> 0 Then
Throw New FormatException("'x^2' was already determined!")
End If
If Not Integer.TryParse(group.Replace("x^2", ""), CoefficientA) Then
' it is there so set it to 1
CoefficientA = 1
End If
Continue For
End If
If group.Contains("x") Then
If CoefficientB <> 0 Then
Throw New FormatException("'x' was already determined!")
End If
If Not Integer.TryParse(group.Replace("x", ""), CoefficientB) Then
CoefficientB = 1
End If
Continue For
End If
If CoefficientC <> 0 Then
Throw New FormatException("CoefficientC was already determined!")
End If
CoefficientC = Convert.ToInt32(group)
Next
End Sub
위의 방법은 당신이 다음 해결할 수 클래스 수준에 필요한 모든 진정한 값을 설정할 것 TryParse 방법을 사용하여, 당신은해야 기분이 텍스트를 표시 표시됩니다 (테스트 케이스 시나리오 참조)
위에서 언급했듯이 최상위 구현에서 다소 벗어 났지만 해결해야 할 방정식이 더 많으면 새로운 클래스를 구문 분석하는 데 더 유연한 접근 방식을 사용할 수 있습니다 (Solve/Resolve 메서드 만 필요함). 그리고 그것은 당신에게 몇 가지 가능한 미래의 문제를 절약 할 수있다 : 리졸있다 D)
테이크, 인터페이스 IEquation를, 및 방법, 그리고 해결 매개 변수
Public Interface IEquation
Sub Resolve(input As String)
Sub Solve()
ReadOnly Property Solved As Boolean
End Interface
그리고 그 클래스의 경우 MustInherit 구현 해결
''' <summary>Abstract implementation of IEquation, offers TryParse & Parse methods,that in their turn refer to the IEquation.Resolve() to do the actual parsing</summary>
''' <remarks>Any implementation of IEquation must have a paramless constructor</remarks>
Public MustInherit Class Equation
Implements IEquation
Public Shared Function TryParse(Of T As {New, IEquation})(input As String, ByRef equation As T) As Boolean
Dim succeeded As Boolean = True
Try
If String.IsNullOrWhiteSpace(input) Then
Throw New ArgumentException("Input string cannot be empty or nothing!", "input")
End If
equation = Parse(Of T)(input)
Catch ex As Exception
equation = Nothing
succeeded = False
End Try
Return succeeded
End Function
Public Shared Function Parse(Of T As {New, IEquation})(input As String) As T
Dim equation As New T()
equation.Resolve(input)
Return equation
End Function
Private _solved As Boolean = False
Public Property Solved As Boolean
Get
Return _solved
End Get
Protected Set(value As Boolean)
_solved = value
End Set
End Property
Public ReadOnly Property SolvedExplicit As Boolean Implements IEquation.Solved
Get
Return Solved
End Get
End Property
Public MustOverride Sub Resolve(input As String) Implements IEquation.Resolve
Public MustOverride Sub Solve() Implements IEquation.Solve
End Class
개 이 클래스는 다음과 같은 이차 방정식으로 생성하고자하는 다른 모든 구문 분석 방정식의 기반으로 사용할 수있는 다음과 같은
으로 테스트 할 것 Public Class QuadraticEquation
Inherits Equation
Private _cA As Integer
Public Property CoefficientA As Integer
Get
Return _cA
End Get
Set(value As Integer)
If _cA = value Then
Return
End If
_cA = value
Solved = False
End Set
End Property
Private _cB As Integer
Public Property CoefficientB As Integer
Get
Return _cB
End Get
Set(value As Integer)
If _cB = value Then
Return
End If
_cB = value
Solved = False
End Set
End Property
Private _cC As Integer
Public Property CoefficientC As Integer
Get
Return _cC
End Get
Set(value As Integer)
If _cC = value Then
Return
End If
_cC = value
Solved = False
End Set
End Property
Private _positiveRoot As Decimal
Public Property PositiveRoot As Decimal
Get
Return _positiveRoot
End Get
Protected Set(value As Decimal)
_positiveRoot = value
End Set
End Property
Private _negativeRoot As Decimal
Public Property NegativeRoot As Decimal
Get
Return _negativeRoot
End Get
Protected Set(value As Decimal)
_negativeRoot = value
End Set
End Property
Public Overrides Sub Resolve(input As String)
' lets say 2x^2 + 4x - 4 = 0
' lets say 5x^2 + 3x + 1 = 0
If String.IsNullOrWhiteSpace(input) Then
Throw New ArgumentException("Input string cannot be null", "input")
End If
If input.IndexOf("=") >= 0 Then
input = input.Split("=")(0).Trim()
If String.IsNullOrWhiteSpace(input) Then
Throw New FormatException("'=' is at the beginning of the equation")
End If
End If
If input.Contains(" ") Then
input = input.Replace(" ", "")
End If
Dim lstGroup As New List(Of String)
Dim position As Integer = 0
Dim delimiters() As String = {"+", "-"}
Dim minIndex As Integer
Dim curDel As String
Dim lastDel As String = "+"
Dim part As String
While position < input.Length
minIndex = input.Length
curDel = "+"
For Each del In delimiters
Dim targetIndex As Integer = input.IndexOf(del, position)
If targetIndex > 0 AndAlso targetIndex < minIndex Then
minIndex = targetIndex
curDel = del
End If
Next
part = input.Substring(position, minIndex - position)
lstGroup.Add(lastDel + part.ToLower())
position = minIndex + 1
lastDel = curDel
End While
CoefficientA = 0
CoefficientB = 0
CoefficientC = 0
For Each group In lstGroup
If group.Contains("x^2") Then
If CoefficientA <> 0 Then
Throw New FormatException("'x^2' was already determined!")
End If
If Not Integer.TryParse(group.Replace("x^2", ""), CoefficientA) Then
' it is there so set it to 1
CoefficientA = 1
End If
Continue For
End If
If group.Contains("x") Then
If CoefficientB <> 0 Then
Throw New FormatException("'x' was already determined!")
End If
If Not Integer.TryParse(group.Replace("x", ""), CoefficientB) Then
CoefficientB = 1
End If
Continue For
End If
If CoefficientC <> 0 Then
Throw New FormatException("CoefficientC was already determined!")
End If
CoefficientC = Convert.ToInt32(group)
Next
End Sub
Public Sub New()
End Sub
Public Overrides Sub Solve()
Solved = False
Try
Dim determinant As Decimal
Dim squareRootDeterminant As Decimal
Dim doubleA As Decimal
determinant = ((CoefficientB^2) - (4 * CoefficientA * CoefficientC))
If determinant >= 0 Then
squareRootDeterminant = Math.Sqrt(Math.Abs(determinant))
Else
Throw New InvalidOperationException("Cannot get Square root of negative determinant " & determinant)
End If
doubleA = 2 * CoefficientA
PositiveRoot = (-CoefficientB + squareRootDeterminant)/doubleA ' quadratic formula root1
NegativeRoot = (-CoefficientB - squareRootDeterminant)/doubleA ' quadratic formula root2
Solved = True
Catch ex As Exception
Solved = False
Console.WriteLine("{0}", ex.Message)
End Try
End Sub
End Class
(다시, 약간 구현을 과장)
Sub Main()
Dim test() As String = {"2x^2 + 4x - 4 = 0", "5x^2 + 3x + 1", "2x^2+5x", "x^2+5", "5x - 5 + 3x^2"}
Dim eq As IEquation = Nothing
For Each expression In test
Console.WriteLine("Trying to resolve: {0}", expression)
If Equation.TryParse(Of QuadraticEquation)(expression, eq) Then
eq.Solve()
If Not eq.Solved Then
Console.WriteLine(vbTab & "Although it could be read, the equation failed to be solved!")
Else
Dim qe As QuadraticEquation = DirectCast(eq, QuadraticEquation)
Console.WriteLine(vbTab & "Result: [{0}; {1}]", qe.NegativeRoot, qe.PositiveRoot)
End If
Else
Console.WriteLine("Couldn't be resolved!")
End If
Next
Console.ReadLine()
End Sub
입력 상자에서 읽으려는 식을 읽을 수 있도록 입력을 구문 분석해야합니다. 귀하의 질문에 관해서는, 당신은 지금까지 무엇을 가지고 있습니까? – Icepickle
입력을 처리하는 데 필요한 함수가 있지만이 텍스트 상자에 붙어 있습니다. – yawar
@icepickle, "... 입력 내용을 구문 분석 할 수 있습니까?" – yawar