-
Notifications
You must be signed in to change notification settings - Fork 0
/
RpnCalculator.php
115 lines (100 loc) · 3.35 KB
/
RpnCalculator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<?php
require_once 'OperandStack.php';
require_once 'NoSuchOperator.php';
require_once 'Add.php';
require_once 'Subtract.php';
require_once 'Factorial.php';
class RpnCalculator
{
//private $accumulator = 0;
//private $values = array(0);
private $values;
public function __construct()
{
$this->values = new OperandStack;
}
public function getAccumulator()
{
return $this->values->peek();
// if(sizeof($this->values)>0) {
// return $this->values[sizeof($this->values)-1];
// //before it was: return $this->accumulator;
// } else return 0;
}
public function setAccumulator($value)
{
$this->values->replaceTop($value);
// if(sizeof($this->values)>0) {
// array_pop($this->values);
// }
// array_push($this->values, $value);
//$this->accumulator = $value;
}
public function enter()
{
$this->values->push($this->getAccumulator());
//array_push($this->values2,$this->getAccumulator());
//array_push($this->values,$this->getAccumulator());
}
public function drop()
{
$this->values->pop();
// if(sizeof($this->values)>0)
// array_pop($this->values);
}
// private function add()
// {
// $rhs = $this->values->peek();
// $this->values->pop();
// $lhs = $this->values->peek();
// $result = $lhs + $rhs;
// $this->values->replaceTop($result);
// }
// private function subtract()
// {
// $rhs = $this->values->peek();
// $this->values->pop();
// $lhs = $this->values->peek();
// $result = $lhs - $rhs;
// $this->values->replaceTop($result);
// }
// private function factorial()
// {
// $operand = $this->values->peek();
// $result = 1;
//
// while($operand > 0)
// {
// $result *= $operand;
// $operand -= 1;
// }
//
// $this->values->replaceTop($result);
// }
public function execute($operatorName)
{
if($operatorName == "+"){
$addobject = new Add;
$addobject->execute($this->values);
//$this->add();
}
else if($operatorName == "-"){
$subtractobject = new Subtract;
$subtractobject->execute($this->values);
//$this->subtract ();
}
else if($operatorName == "!"){
$factorialobject = new Factorial;
$factorialobject->execute($this->values);
//$this->factorial ();
}
else {
try{
throw new NoSuchOperator('No such operator!');
} catch (NoSuchOperator $e) {
echo 'Caught exception: '.$e->getMessage();
}
}
}
}
?>