Let me try and ask a question
Nevermind the expression array, I'm so confused. Let's play with this code:
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import org.omg.CORBA.Current;
class Prog3<T> extends MyArrayList<T> {
// method compares operators to establish precedence
private static int prec(char x) {
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/' || x == '%')
return 2;
return 0;
}
public static void main (String args [])
{
Stack operatorStack = new Stack();
Stack operandStack = new Stack();
BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in));
String line = null;
while (true){
System.out.print("Enter an expression: ");
try{
line = keyboard.readLine();
}catch(IOException e){}
for(int i=0; i < line.length(); i++){
if(line.charAt(i) == ' '){
}else if(line.charAt(i) == '/'){
operatorStack.push('/');
}else if(line.charAt(i) == '*'){
operatorStack.push('*');
}else if(line.charAt(i) == '+'){
operatorStack.push('+');
}else if(line.charAt(i) == '-'){
operatorStack.push('-');
}else if(line.charAt(i) >= 97 && line.charAt(i) <= 109){
operandStack.push(line.charAt(i));
}
}
System.out.println(operatorStack);
System.out.println(operandStack);
}
}
}
Here is an example of what happens when I run the program.
Enter an expression: a + b - c / d * f
[+, -, /, *]
[a, b, c, d, f]
The operators and operands get popped to the respective stacks that I created. All I need to do now, is put the expression in postfix notation. I want to use the prec method to do so. How can I do this?