i am working on a program using stacks. what i have so far is reading in the line and pushing operands/operators into their respective stacks. My teacher has us using a MyArrayList class, therefore we have to extend to that class and use its methods instead of using the Stack methods from the api. I was wondering how I can refer to the top of a stack? I want to use a similar method such as the peek method from the Stack api that would let me know what is at the top. This is what I have so far:
import java.io.*;
class Prog3<T> extends MyArrayList<T>{
static int p1;
public static int prec(char op1){
if(op1 == '*' || op1 == '/') p1=2;
if(op1 == '+' || op1 == '-') p1=1;
p1=0;
return p1;
}
public static void main (String[] args){
MyArrayList<Character> operators = new MyArrayList<Character>();
MyArrayList<Character> operands = new MyArrayList<Character>();
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while(true){
System.out.print("Enter an expression: ");
try{
line = keyboard.readLine();
char a=97;
char m=109;
char op1, op2;
for(int i=0; i < line.length(); i++){
if(line.charAt(i) == ' '){
;
}else if(line.charAt(i) == '/'){
op1 = (Character) operators.peek();
op2 = '/';
if(operators.isEmpty()){
operators.push('/');
}else if(prec(op2) >= prec(op1)){
operators.push(op2);
}else {
operators.pop();
operators.push(op2);
}
}else if(line.charAt(i) == '*'){
op2 = '*';
operators.push('*');
}else if(line.charAt(i) == '+'){
op2 = '+';
operators.push('+');
}else if(line.charAt(i) == '-'){
op2 = '-';
operators.push('-');
}else if(line.charAt(i) >= a && line.charAt(i) <= m){
operands.push(line.charAt(i));
}
}
}catch(IOException e){}
if(line.equals("end")) return;
System.out.println(operators);
System.out.println(operands);
}
}
}