Home   Cover Cover Cover Cover
 

Calculator

Chap4_Ex3.cs
using System;
using System.Collections;

public class StackCalculator {
  private Stack stack;

  public StackCalculator() { 
    stack = new Stack();
  }

  public void Push(int x) { stack.Push(x); }
 
  public int Pop() { return (int) stack.Pop(); }

  public void Add() { stack.Push((int)stack.Pop()+(int)stack.Pop()); }

  public void Sub() { stack.Push((int)stack.Pop()-(int)stack.Pop()); }

  public void Mul() { stack.Push((int)stack.Pop()*(int)stack.Pop()); }

  public void Div() { stack.Push((int)stack.Pop()/(int)stack.Pop()); }

  public void Flush() { stack.Clear(); }
  
  public static void Main(string[] args) {
    StackCalculator calc = null;
    string cmd = "";
    string carg = "";
    Console.Write("cmd?:");
    while(!cmd.Equals("exit")) {
      
      string line = Console.ReadLine().Trim();
      int pos = line.IndexOf(" ");
      if(pos!=-1) {
        cmd = line.Substring(0,pos);
        carg = line.Substring(pos,line.Length-pos);
      }
      else cmd = line;
      try {
        if(cmd == "create") {
          calc = new StackCalculator();
          Console.Write("calculator created\ncmd?:");
        }
        else if(cmd == ("push")) {
          int a = Int32.Parse(carg.Trim());
          calc.Put(a);
          Console.Write("pushed {0}\ncmd?:",a);
        }
        else if(cmd == "get") { 
          Console.Write("{0}\ncmd?:",calc.Pop());
        }
        else if(cmd == "add" ) { 
          calc.Add();
          Console.Write("addition performed\ncmd?:");
        }
        else if(cmd == "sub") { 
          calc.Sub();
          Console.Write("subtraction performed\ncmd?:");
        }
        else if(cmd == "mul") { 
          calc.Mul();
          Console.Write("multiplication performed\ncmd?:");
        }
        else if(cmd == "div") { 
          calc.Div();
          Console.Write("division operation performed\ncmd?:");
        }
        else if(cmd == "flush") { 
          calc.Flush();
          Console.Write("calculator stack flushed\ncmd?:");
        }
        else {
          Console.Write("command not found\ncmd?:");
        }
      } catch(InvalidOperationException e) {
        Console.Write("invalid operation stack empty!\ncmd?:");
      } catch(NullReferenceException ex) {
        Console.Write("create calculator first!\ncmd?:");
      }

    }
  }
}