0
我的代碼成功地將中綴表達式轉換爲後綴表達式。但是,當我輸入的數字超過1位數時(例如546),我在這個數字和右邊的操作數之間沒有空格。後綴表達式輸出中缺少空格 - Java
我的代碼的測試運行: 輸入:輸入表達式:(24/4)/(15/3)* 10 - 4 + 2 輸出:後綴表達式爲:244/153// 10 * 4 - 2+
我想它是後綴表達式是:24 4/15 3// 10 * 4 - 2+
這是我的代碼:請建議,讓我的任何變化在輸出中插入空格。
import java.util.*;
public class PostfixConversion {
public static void main(String args[]) {
System.out.print("Enter an expression: ");
String infix = new Scanner(System.in).nextLine();
System.out.println(convertToPostfix(infix));
}
public static boolean precedence(char first, char second)
{
int v1 = 0, v2 = 0;
//find value for first
if(first == '-' || first == '+'){
v1 = 1;
}else if(first == '*' || first == '/'){
v1 = 2;
}//end if
//find value for second
if(second == '-' || second == '+'){
v2 = 1;
}else if(second == '*' || second == '/'){
v2 = 2;
}//end if
if(v1 < v2){
return false;
}//end if
return true;
}//end precedence method
//converts infix expression into postfix expression
public static String convertToPostfix(String infixExp)
{
String postFix = "The Postfix Expression is: ";
Stack<Character> stack = new Stack<Character>();
char character = ' ';
for(int i = 0; i < infixExp.length(); i++)
{
character = infixExp.charAt(i);
//determine if character is an operator
if(character == '*' || character == '-' || character == '/' || character == '+')
{
while(!stack.empty() && precedence(stack.peek(), character)){
postFix += stack.pop();
}//end while
stack.push(character);
}
else if(character == '(') //check for left parenthesis
{
stack.push(character);
}
else if (character == ')')
{
while(!stack.peek().equals('(') && !stack.isEmpty()){ //add characters until left parenthesis
postFix += stack.pop();
}//end while
if(!stack.isEmpty() && stack.peek().equals('(')){
stack.pop(); // pop/remove left parenthesis
}
}
else
{
postFix += character;
}//end if
}//end for
while(!stack.empty()) //add the remaining elements of stack to postfix expression
{
if(stack.peek().equals('('))
{
postFix = "There is no matching right parenthesis.";
return postFix;
}
postFix += stack.pop();
}
return postFix;
}//end convertToPo
}
[什麼是調試器,它如何幫助我診斷問題?](https://stackoverflow.com/q/25385173/5221149) – Andreas
查找Djkstra分流碼算法的一些現有實現,以查看'precedence()'方法應該是真的實現。它並沒有你所做的那麼複雜。 – EJP