An Eclipse project contains resources.
A package is a resource.
A package contains classes, interfaces, and subpackages.
A class contains fields and methods.
Start Eclipse and create a new Java project:
File>new>Java Project...
Name the new project "Stack Machine".
Next add a new package called "logic" to the project:
File>new>package...
Note, almost every Eclipse object has a shortcut menu that can be displayed by right clicking on the object's icon. The last item on the shortcut menu is the property sheet for the object.
We can add a new package to a project by selecting new>package from the project's shortcut menu.
My notation:
Stack Machine>>new>package...
Add a new class called StackMachine to the logic package:
File>new>class...
or
logic>>new>class...
Make sure the class is added to the correct package.
public class StackMachine extends Stack<Double> {
}
Note that Eclipse detects an error in this line. This is because Stack comes from the java.util package. Double click on the error and Eclipse should automatically insert the appropriate import command into your code.
Note, this could have been done by specifying the superclass in the New Java Class dialog.
Why not extend Stack or Stack<double>?
What are the advantages and disadvantages with extending Stack versus supplying StackMachine with a Stack field:
public class StackMachine {
private Stack<Double> operands =
new Stack<Double>();
}
Add the following method declaration to the StackMachine class:
public void add() throws
Exception {
if (size() < 2) {
throw new Exception("stack
needs at least 2 numbers");
}
double arg1 = pop();
double arg2 = pop();
push(arg1 + arg2);
}
Repeat this procedure for mul, div, and sub.
Compare the following error handling strategies to throwing an exception:
public void add() throws
Exception {
if (2 < size()) {
double
arg1 = pop();
double
arg2 = pop();
push(arg1
+ arg2);
}
}
public void add() throws
Exception {
if (size() < 2) {
System.err.println("stack
needs at least 2 numbers");
System.exit(1);
}
double arg1 = pop();
double arg2 = pop();
push(arg1 + arg2);
}
How shall we prevent division by zero?
How can Doubles be stored as doubles and vice versa?