JAVA RPn 解析器
else if (token.equals("-")) {
op2 = stack.pop();
op1 = stack.pop();
stack.push(op2*-1);}
如果我输入的是“-4”或数字前面有减号的东西,它会带来错误
任何的想法?
else if (token.equals("-")) {
op2 = stack.pop();
op1 = stack.pop();
stack.push(op2*-1);}
如果我输入的是“-4”或数字前面有减号的东西,它会带来错误
任何的想法?
如果要在 RPN(反向波兰表示法)中解析负数,则需要在将数字推送到堆栈之前在解析器中检测 then。
如果您正在阅读减号并且下一个符号(在空格之前)是一个数字,它将是数字的一部分。看一看:
import java.util.*;
public class RPNParser {
public static void main( String[] args ) {
String rpnExp = "-4 3 + 5 * 3 - -61 *";
String[] tokens = rpnExp.split( " " );
Stack<Integer> stack = new Stack<Integer>();
Integer op1 = null;
Integer op2 = null;
Integer result = null;
for ( String token : tokens ) {
if ( token.equals( "+" ) ) {
op2 = stack.pop();
op1 = stack.pop();
stack.push( op1 + op2 );
} else if ( token.equals( "-" ) ) {
op2 = stack.pop();
op1 = stack.pop();
stack.push( op1 - op2 );
} else if ( token.equals( "*" ) ) {
op2 = stack.pop();
op1 = stack.pop();
stack.push( op1 * op2 );
} else if ( token.equals( "/" ) ) {
op2 = stack.pop();
op1 = stack.pop();
stack.push( op1 / op2 );
} else {
stack.push( Integer.valueOf( token ) );
}
}
result = stack.pop();
System.out.printf( "%s = %d\n", rpnExp, result );
}
}
如您所知:
-4 3 + 5 * 3 - -61 * = ((((-4 + 3) * 5) - 3) * -61) = 488
postfix infix result
如果您想手动解析您的字符串(不使用拆分),您将需要做更多的工作,但这真的很容易。
String rpnExp = "-4 3 + 5 * 3 - -61 *";
StringBuilder newToken = new StringBuilder();
List<String> tokens = new ArrayList<String>();
for ( char c : rpnExp.toCharArray() ) {
// the current char is a space?
if ( c == ' ' ) {
// yes, it is.
// the new token has something?
if ( newToken.length() > 0 ) {
// yes, it has
// add its value to the token list
tokens.add( newToken.toString() );
// resets new token
newToken = new StringBuilder();
}
} else { // c is not a space
// yes, so add it to the newToken
newToken.append( c );
}
}
// needs to process the last value of newToken
// so, if it has something
if ( newToken.length() > 0 ) {
// add the value to the token list
tokens.add( newToken.toString() );
}
Stack<Integer> stack = new Stack<Integer>();
// the rest of the code here ...