I have a program where I'm trying to concatenate token objects with string, using operands (numbers and variables) and operators (+, -, *, /):
private static Token evalOp(Token op, Token t1, Token t2) {
return "Operator: [" + op + "]; Operand1: [" + t1 +"]; Operand2 [" + t2 + "]";
}
I have a separate array of tokens, that I'm trying to add onto.
private static ArrayList<Token> infixToPostfix(ArrayList<Token> intokens) {
String string = "";
Stack s = new Stack();
for (int i = 0; i < s.length(); i++){
if (intokens[i]==operand){
string+=intokens[i];
}
else if (intokens[i]==operator){
while (!s.empty()/*&&hasHigherPrecedence(s.top(), intokens[i])*/){
string+=s.pop();
s.pop();
}
s.push(intokens[i]);
}
}
}
Its for an infix to postfix program. I want to convert infix to postfix and display it in an array. I originally thought the problem had to do with concatenating strings and numbers, but I now believe I was wrong. You'll notice the first code was just replaced. That's because the old code had several if-statements that concatenated numbers and tokens. The tokens could be numbers or variables. I sort of forgot and made the stupid mistake treating it above like they were numbers.
Anyways, I want the user to enter an infix expression, like
2 * 3 + 5
and convert it to
2 3 * 5 +
See what I mean? It takes in an expression, then it returns it as a postfix expression. But the postfix expression needs to have these types of strings around it, so the output would really be:
[num: 2], [num: 3], [op: *], [num: 5], [op: +]
See what I mean? I also have another function in my code, in addition to the main method for making an arrayList of token:
private static ArrayList<Token> parse(String s) {
// make a loop and take each char out of the String s, one by one and check
// to see what token type it is. Then store the token type in an ArrayList of tokens
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
String v = Character.toString(c);
TokenType t = getTokenType(c);
if (t==null){
//print error
System.out.println("Error");
}
else if(!t.equals(TokenType.WS)){
//add to array
list.add(TokenType.WS);
}
}
return list;
}
I have more code, but basically, I want to convert infix to postfix and I want to evaluate it. It has to pass this algorithm as a test:
class SimpleCalcTest {
public static void test() {
String[] inputs = {
"3*4 + 5",
"3 + 4*5",
"(1+1)*(5-2)",
"(3*4+5)*(3*3 + 4*4)"
};
for (int i=0; i<inputs.length; i++) {
String s = inputs[i];
System.out.println();
System.out.println();
System.out.println("test: input = " + s);
String r = SimpleCalc.evalExpression(s);
System.out.println("\tresult = " + r);
}
}
public static void main(String[] args) {
SimpleCalc.commandLine();
}