Assignment 5

RPN calculator

by Taylor Zimmerman

HTML

<html>
<body>
<h1>
RPN Calculator
</h1>
<fieldset>
<legend>
First enter two numbers to stack</legend>
<input type="number" id="tbInput"><br>
<input type="button" value="Push Value" onclick="Push()">
<input type="button" value="Pop Value" onclick="Pop()">
</fieldset>
<fieldset>
<legend>Second apply operand</legend>
<input type="button" value="+" onclick="Add()">
<input type="button" value="-" onclick="Subtract()">
<input type="button" value="*" onclick="Multiply()">
<input type="button" value="/" onclick="Divide()">
</fieldset>
<fieldset>
<legend>Display Calculations</legend>
<div id="output"><br>
</div>
<div id="Message">
</div>
</fieldset>
</body>
</html>

JavaScript

var str;
var Node = function(_content){
	this.next = null;
  this.last = null;
  this.content = _content;
}

var Stack = function(){
	this.length = 0;
	this.head = null;
  this.top = null;
  }
  
Stack.prototype.push = function(_content){

  	if(this.top == null){
    	this.top = new Node(_content);
      this.head = this.top;
      return this;
    }
    var addedNode = new Node(_content);
    addedNode.last = this.head;
    
    this.head.next = addedNode;
    this.head = addedNode;
    return this;
    
  }
Stack.prototype.pop = function(){

   if(this.top == null){
    	alert("The stack is empty");
      return null;
    }
    if (this.top == this.head) {
    this.top = null;
    this.head = null;
    return this.head;
    }
    var a = this.head
    this.head = this.head.last;
    this.head.next = null;
    return a;
    
   
  }
    
Stack.prototype.toString = function(){
	
    var node = this.head;
    str = " ";
    while(node != null){
    	str += node.content + "<br>" ;
      node = node.last;
    }

    return str;
  
}

var stack = new Stack();

function Push(){
var tb = parseFloat(document.getElementById('tbInput').value);
 if (isNaN(tb)){
	str = "Please enter a Number";
  document.getElementById('output').innerHTML = str;
  document.getElementById('Message').innerHTML = " ";
  return false;
}

stack.push(tb);
  document.getElementById('output').innerHTML = stack.toString();
}
function Pop() {
  stack.pop();

  document.getElementById('output').innerHTML = stack.toString();
  document.getElementById('Message').innerHTML = " ";
  }
 
function Add(){
var x = parseFloat(stack.top.next.content);
var y = parseFloat(stack.top.content);
var answer = (x + y);
stack.pop();
stack.pop();
stack.push(answer);
str ="The number " + x + " was added to " + y + " and equals " + answer;
parseFloat(document.getElementById('Message').innerHTML = str);
parseFloat(document.getElementById('output').innerHTML = stack.toString())
}

function Subtract(){
var x =...