Hi, I am supposed to write a program that will evaluate postfix expressions using a linked list stack. The user will input the expression on the command line and I have to check if each part of the input is either a operand or an operator. I've gotten the program to compile, but it won't do anything. I think I made a mistake with checking the user input. Any advice is greatly appreciated! Thank you!
import java.util.*; public class Calc<T> implements Stack<T> { private int position; private Node<T> head; public Calc() { position = 0; head = null; } public int size() { return position; } public boolean isEmpty() { return size() == 0; } public void push(T item) { if(head == null){ Node<T> newNode; newNode = new Node<T>(item); newNode.setNext(head); head = newNode; position++; }else{ Node<T> newNode; newNode = new Node<T>(item); newNode.setNext(head); head = newNode; position++; } } public T pop() throws StackEmptyException { if(isEmpty()) { throw new StackEmptyException("Stack empty"); } T val = head.getItem(); remove(); return val; } public T peek() throws StackEmptyException { if(isEmpty()){ throw new StackEmptyException("Stack empty"); } return head.getItem(); } public void makeEmpty() { head = null; position = 0; } public void remove() { if(position == 1) { head = null; position = 0; }else{ head = head.getNext(); position--; } } public static void add(Stack<Integer> s){ try{ int n = s.pop(); int m = s.pop(); n =+ m; s.push(n); }catch(StackEmptyException e) { } } public static void sub(Stack<Integer> s){ try{ int n = s.pop(); int m = s.pop(); n = n - m; s.push(n); }catch(StackEmptyException e) { } } public static void divide(Stack<Integer> s){ try{ int n = s.pop(); int m = s.pop(); n = n/m; s.push(n); }catch(StackEmptyException e) { } } public static void times(Stack<Integer> s){ try{ int n = s.pop(); int m = s.pop(); n =n*m; s.push(n); }catch(StackEmptyException e) { } } public static void main(String[]args){ Scanner input = new Scanner(System.in); Stack<Integer> s1 = new Calc<Integer>(); while(input.hasNext()){ if(input.next().equals('+')){ add(s1); }else if(input.next().equals('-')){ sub(s1); }else if(input.next().equals('/')){ divide(s1); }else if(input.next().equals('x')){ times(s1); }else{ s1.push(input.nextInt()); } } System.out.println(s1); } }
interface Stack
public interface Stack<T> { int size(); boolean isEmpty(); void push (T element); T pop() throws StackEmptyException; T peek() throws StackEmptyException; void makeEmpty(); }