大家好,我有一个新问题 x =平方根,c = cos 我怎么能:x((1 - c(30))/ 2)后缀:1 30 c - 2 / x,它给了我这个后缀:1 30 2 / c - x
如何将所述中缀转换为所述后缀?我应该做什么优先或相关性?我想在我的程序中使用的一元运算符的中缀应该是运算符(值),我希望它在两者之间有一个括号。我试图制作科学的计算器,这就是为什么
编辑:这就是我拥有的,我应该改变或制作什么?
private static final int L_ASSOC = 0;
private static final int R_ASSOC = 1;
private static final Map<String, int[]> OP = new HashMap<String, int[]>();
static {
OP.put("+", new int[] { 0, L_ASSOC });
OP.put("-", new int[] { 0, L_ASSOC });
OP.put("*", new int[] { 5, L_ASSOC }); //Precedence, Associativity
OP.put("/", new int[] { 5, L_ASSOC });
OP.put("%", new int[] { 10, L_ASSOC });
OP.put("x", new int[] { 10, R_ASSOC });
OP.put("s", new int[] { 10, R_ASSOC });
OP.put("c", new int[] { 10, R_ASSOC });
OP.put("t", new int[] { 10, R_ASSOC });
OP.put("^", new int[] { 10, R_ASSOC });
}
public static boolean IsASSOC(String Token, int Type){
if (!IsOP(Token)) {
throw new IllegalArgumentException("Invalid token: " + Token);
}
if (OP.get(Token)[1] == Type) {
return true;
}
return false;
}
private static final int GetPrecedence(String T1, String T2) {
if (!IsOP(T1) || !IsOP(T2)) {
throw new IllegalArgumentException();
}
return OP.get(T1)[0] - OP.get(T2)[0];
}
public static boolean IsOP(String Token){
return OP.containsKey(Token);
}
public static String[] Infix2Postfix(String[] infix) {
ArrayList<String> Postfix = new ArrayList<String>();
Stack<String> OperatorStack = new Stack<String>();
for ( String tkn: infix ){
if (IsOP(tkn)){
while (!OperatorStack.empty() && IsOP(OperatorStack.peek())) {
if (( IsASSOC(tkn, L_ASSOC) && GetPrecedence(tkn, OperatorStack.peek()) <= 0 )
||
(IsASSOC(tkn, R_ASSOC) && GetPrecedence(tkn, OperatorStack.peek()) < 0))
{
Postfix.add(OperatorStack.pop());
continue;
}
break;
}
OperatorStack.push(tkn);
} else if (tkn.equals("(")) {
OperatorStack.push(tkn);
} else if (tkn.equals(")")) {
while (!OperatorStack.empty() && !OperatorStack.peek().equals("(")) {
Postfix.add(OperatorStack.pop());
}
} else {
Postfix.add(tkn); // [S12]
}
}
while (!OperatorStack.empty()) {
if (IsOP(OperatorStack.peek())==false){
String s = OperatorStack.pop();
continue;
}
Postfix.add(OperatorStack.pop());
}
String[] output = new String[Postfix.size()];
return Postfix.toArray(output);
}
我的解决方案:
else if (tkn.equals(")")) {
while (!OperatorStack.empty() && !OperatorStack.peek().equals("(")) {
Postfix.add(OperatorStack.pop());
}
OperatorStack.pop(); //I Simply popped after the while loop to remove the matching open parenthesis
}