Let's say I have String "50". With the following code at the end of the post I loose the 0 of the 50 since I used .charAt(0). How can I avoid this?
Additional info :
I have String[] s, which has the numbers in it [2],[5],[50]. The problem is I cannot convert 50 to char. I can easily say,
char ch = s[i].charAt(0);
but this would loose the 0 at the end of the 50. I need this for postfix to infix converter. My converter works great except for the double digits. Here it is so far. With this code below, I can easily convert 2+5+7. But if I write 2+50 the postfix will be 250+. It is correct but later I will create an expression tree from this and evaluate. When creating the tree, the elements of the tree becomes 2,5,0,+ not 2,50,+. So, I have come up with a solution to store my infix elements in String[] array. But I need help converting it to postfix.
public class infix2post {
public String infix2post(String infix) {
Stack s = new Stack();
char ch, ch2;
String postfix = "";
for (int i = 0; i < infix.length(); i++) {
ch = infix.charAt(i);
if (ch >= 48 && ch <= 57)
postfix += ch;
else if (ch == '(')
s.push(ch);
else if (ch == ')') {
ch2 = s.pop();
while (ch2 != '(') {
postfix += ch2;
ch2 = s.pop();
}
} else {
while (priority(ch) <= priority(s.top())) {
ch2 = s.pop();
postfix += ch2;
}
s.push(ch);
}
}
while (!s.isEmpty()) {
ch = s.pop();
postfix += ch;
}
return postfix;
}
public int priority(char ch) {
if (ch == '+' || ch == '-')
return 1;
else if (ch == '*' || ch == '/' || ch == '%')
return 2;
else
return 0;
}
}
Aucun commentaire:
Enregistrer un commentaire