我正在开发一个解决算术方程的程序。
方程的一个例子是:
4+(5/4)+3/((5/3-2.4(*(5-7))
我有一个程序可以将此等式从中缀形式转换为后缀形式,但该程序将2.4
.
它将 2 和 4 视为单独的数字,它们应该被视为一个数字。我将如何解决这个问题?
import java.util.EmptyStackException;
import java.util.Scanner;
import myUtil.*;
public class InfixToPostfix extends Asg6
{
public static class SyntaxErrorException extends Exception
{
SyntaxErrorException(String message)
{
super(message);
}
}
private AStack<Character> operatorStack;
private static final String operators = "+-*/^()";
private static final int[] precedence =
{
1, 1, 2, 2, 3, -1, -1
};
private StringBuilder postfix;
public String convert(String infix) throws SyntaxErrorException
{
operatorStack = new AStack<Character>();
postfix = new StringBuilder();
try
{
String nextToken;
Scanner scan = new Scanner(infix);
while ((nextToken = scan.findInLine("[\\p{L}\\p{N}]+|[-+/\\*^()]")) != null)
{
char firstChar = nextToken.charAt(0);
if (Character.isJavaIdentifierStart(firstChar) || Character.isDigit(firstChar))
{
postfix.append(nextToken);
postfix.append(' ');
}
else if (isOperator(firstChar))
{
processOperator(firstChar);
}
else
{
throw new SyntaxErrorException("Unexpected Character: " + firstChar);
}
}
while (!operatorStack.empty())
{
char op = operatorStack.pop();
if (op == '(')
{
throw new SyntaxErrorException("Unmatched parenthesis");
}
postfix.append(op);
postfix.append(' ');
}
return postfix.toString();
}
catch (EmptyStackException ex)
{
throw new SyntaxErrorException("Syntax Error: The stack is empty");
}
}
private void processOperator(char op)
{
if (operatorStack.empty() || op == '(')
{
operatorStack.push(op);
}
else
{
char topOp = operatorStack.peek();
if (precedence(op) > precedence(topOp))
{
operatorStack.push(op);
}
else
{
while (!operatorStack.empty() && precedence(op) <= precedence(topOp))
{
operatorStack.pop();
if (topOp == '(')
{
break;
}
postfix.append(topOp);
postfix.append(' ');
if (!operatorStack.empty())
{
topOp = operatorStack.peek();
}
}
if (op != ')')
{
operatorStack.push(op);
}
}
}
}
private boolean isOperator(char ch)
{
return operators.indexOf(ch) != -1;
}
private int precedence(char op)
{
return precedence[operators.indexOf(op)];
}
}