问题描述
我正在使用堆栈来转换具有以下表达式的数组:所有数字,方括号和运算符都以infix顺序分开。我将此数组传递给“ topPostFix”方法,该方法使用堆栈将数组按后缀顺序转换为String表达式。
`public static String toPostFix(String[] postfixArray){ //converts to post fix with seperated string
Stack <String> stackPost = new Stack();
String posst;
StringBuilder buildtest = new StringBuilder("");
for(int i=0; i<(postfixArray.length);i++){
if (isNum(postfixArray[i])){
buildtest.append(postfixArray[i]);
buildtest.append(" ");
}
else if(isOperator(postfixArray[i])){
while(!stackPost.empty() && stackPost.peek()!="(" &&higherPresedance((stackPost.peek()),postfixArray[i])){
buildtest.append((stackPost.peek()));
buildtest.append(" ");
stackPost.pop();
}
stackPost.push(postfixArray[i]);
}
else if(postfixArray[i]=="("){
stackPost.push(postfixArray[i]);
}
else if(postfixArray[i]==")"){
while(!stackPost.empty()&&stackPost.peek()!="("){
buildtest.append(stackPost.peek());
buildtest.append(" ");
stackPost.pop();
}
stackPost.pop();
}
}
while(!stackPost.empty()){
buildtest.append((stackPost.peek()));
buildtest.append(" ");
stackPost.pop();
}
System.out.println(buildtest);
posst=buildtest.toString();
return posst;
}`
I have individually tested the isNum,isOperator,higherPrecedance methods etc and I kNow they all work individually.
When I pass a test array e.g.(String[] testPost = {"(","-5.4","-","3",")","*","2"}; the result comes out as expected (-5.4 3 - 2 *)
However in my code I want the user to be able to pass a string into the program so I convert the string into the array which when using Arrays.toString(string_converted_to_array). shows up to be '[(,-5.4,-,3,),*,2]'
Where each of the elements in this array is a string.
I have also printed the elements individually using for loops and each element came out on its own without a space.
However when I pass this "string_converted_to_array" into my toPostFix method it does not come out in the correct postfix notation but instead as -5.4 3 2 * -
I have searched all over the internet and I sincerely promise I have tried all I can to find a solution. Please forgive me if this has already been answered and thank you for you time in advance if you try to find a solution to my problem. If anything needs clarification please let me kNow.
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)