[英]how do I add unary operator for RPN algorithm that calculates postfix expression in java
[英]How do we evaluate the postfix string with the unary operator?
如何使用內部的一元運算符評估后綴字符串? 例如:input =“-3.4 + 4.2 * 5” input =“ 3.4 + -4.2 * 5”
我嘗試了以下代碼,但它給我類似以下錯誤消息:java.lang.Number格式異常:空字符串
Java結果:1
這是代碼:
public class PostfixEvaluation {
private Stack<Double> st = new Stack<Double>();
private String[] input;
//Constructor
public PostfixEvaluation(String[] postfixExpression) {
input = postfixExpression;
}
public Double Evaluation(){
for (int i = 0; i < input.length; i++) {
String symbol=input[i];
if (isOperator(symbol)) {
// Operator, simply pop out two numbers from stack and perfom operation
// Notice the order of operands
switch (symbol) {
case "+": st.push(st.pop() + st.pop()); break;
case "*": st.push(st.pop() * st.pop()); break;
case "-":
st.push(-st.pop()+st.pop());
break;
case "/": st.push(1 / st.pop() * st.pop()); break;
}
}
else
{
// Number, push to the stack
st.push(Double.parseDouble(symbol));
}
}
// The final result should be located in the bottom of stack
// Otherwise return 0.0
if (!st.isEmpty())
return st.pop();
else
return 0.0;
}
/**
* Check if the character is an operator
*/
public boolean isOperator(String element) {
if (element.equals( "*" ) || element.equals( "-" )|| element.equals( "/" )||element.equals( "+" )) {
return true;
} else {
return false;
}
}
}
//對於輸入字符串,我將其轉換為
StringBuilder sb2 = new StringBuilder();
for (char c : postfixString.toCharArray()) {
if (!Character.isDigit(c) && c != '.') {
sb2.append(" ").append(c).append(" ");
} else {
sb2.append(c);
}
}
String[] arr2 = sb2.toString().split("\\s+");
PostfixEvaluation answer= new PostfixEvaluation(arr2);
將輸入拆分為數組的算法將生成帶有空字符串的數組。
給定輸入=“ -3.4 + 4.2 * 5”,您將最終將以下數組傳遞給PostfixEvaluation的構造函數:
[,-,3.4,+,4.2,*,5]
該數組的第一個元素是一個空字符串,在您的Evaluation for循環中未考慮。
修改算法以避免將空字符串傳遞給評估程序,或者在for循環中檢查空字符串並忽略它們。
下次的PS Pro技巧:將其他代碼添加到您的原始問題中,而不是將其發布到注釋中,更易於閱讀。
編輯
關於有關建立帶符號操作數的問題,您需要跟蹤是否應該創建操作數或運算符。
private static boolean isOperandChar(final char c) {
return Character.isDigit(c) || c == '.';
}
private static String[] splitPostfixExpression(final String input) {
final List<String> postfixExpression = new ArrayList<>();
boolean encounteredOperandStart = false;
String currentOperand = "";
for(final char c : input.toCharArray()) {
if(encounteredOperandStart) {
if(isOperandChar(c)) {
currentOperand += c;
} else {
// we've encountered an operator char after reading one or more operand characters,
// thus we know this character is an operator and not an operand sign
postfixExpression.add(currentOperand);
postfixExpression.add(String.valueOf(c));
currentOperand = "";
encounteredOperandStart = false;
}
} else {
if(isOperandChar(c)) {
encounteredOperandStart = true;
}
currentOperand += c;
}
}
if(!currentOperand.isEmpty()) {
postfixExpression.add(currentOperand);
}
return postfixExpression.toArray(new String[postfixExpression.size()]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.