I have used a subroutine to prioritize between the operators:
static int p(char c){
if ((c=='+') || (c=='-')) {
return 0;
}
else if ((c=='/') || (c=='*')) {
return 1;
}
else {
return -1;
}
}
I have worked on the code a bit. I'm supposed to follow this transformation: transformation. for i=1 to m if c_i is an operand: Transfer c_i to output.
if c_i is a left parentheses: Push c_i to temp.
if c_i is a right parentheses: Pop elements from temp and transfer them to output until a left-parentheses is met. Pop left-parentheses.
if c_i is an operator: Let the top temp element be t. Pop and transfer elements from temp to output until: p(t) < p(c_i) or
t is a left-parentheses or
temp is empty.
Push c_i to temp.
Transfer the remaining elements in temp to output.
Problems: 1- I'm basically stuck how to do continue if the the digit is an operator. I'm stuck with the 3rd and 4th steps in the above list. 2- The part with THE TWO ASTERISKS is where I have no idea what to do!
The program should convert infix to postfix. From ((3 + 5 1)=8) 14 to 3 5 1 +8 = 14.
THANKS IN ADVANCE!
Remarks and Notation: -The pop operation removes the first element of the string each time it is applied. The top element of a string is the first element of the string. The push operation appends an element in the beginning of the string.
-You can use the methods Integer:parseInt(s) and Character:getNumericV alue(c) to convert a string s and a character c to an integer value, if needed.
-You are not allowed to use data structures other than Strings to manipulate the expressions.
static String infixToPostfix(String infix){
String postfix = "";
infix = readLine();
String temp ="";
char t;
for (int i=0 ; i<infix.length(); i++) {
t = temp.charAt(0);
if (infix.charAt(i) !=')' && infix.charAt(i)!= '(' && infix.charAt(i)!= p(infix.charAt(i)))
postfix += infix.charAt(i);
if (infix.charAt(i) == '+') {
while ( (p('+') <= p(t)) && (t != '(') && (!temp.equals("") ) ){
}
postfix = postfix + temp.charAt(i);
}
if (infix.charAt(i) == '-') {
while ( (p('-') <= p(t)) && (t != '(') && (!temp.equals("") ) ){
postfix = postfix + temp.charAt(i);
}
}
else if (infix.charAt(i) == '*') {
while ( (p('*') <= p(t)) && (t != '(') && (!temp.equals("") ) ){
postfix = postfix + temp.charAt(i);
}}
***if (infix.charAt(i) == '/') {
while ( (p('/') <= p(t)) && (t != '(') && (!temp.equals("") ) ){
postfix = postfix + temp.charAt(i);
}}
if (infix.charAt(i) == '(') {
temp = infix.charAt(i)+temp;
}
if (infix.charAt(i) == ')') {
infix = temp;***
}
}
return postfix;
}