Create a package called presentation.
Add a class called StackMachineCUI. This class should have a main method.
A console user interface (CUI) is driven by a perpetual loop of the form:
while(true) {
�� read next command
�� if command is quit then break
�� execute command
�� print result
}
While System.out is barely adequate for console output, System.in is totally inadequate. We can enhance it by wrapping it in a scanner:
Scanner kbd = new Scanner(System.in);
Scanners have many useful methods for extracting tokens from strings and streams.
For example:
String command = kbd.next(); // command = next token in System.in
double operand = kbd.nextDouble();
Before we can complete our control loop we must decide on the commands we will execute and their syntax and semantics.
Assume sm is some stack machine:
StackMachine sm = new StackMachine();
Here is a list of commands for the stack machine and their interpretations:
quit // terminate program
push NUMBER // sm.push(NUMBER)
pop // sm.pop()
top // display sm.peek()
add // sm.add()
mul // sm.mul()
sub // sm.sub()
div // sm.div()
Here's a basic control loop. Finish it by replacing the ??? comments:
�� public
static void
main(String[] args) {
����� StackMachine sm = new StackMachine();
����� Scanner kbd = new Scanner(System.in);
����� while(true) {
�������� System.out.print("-> ");
�������� String command = kbd.next();
�������� String result = "done";
�������� if
(command.equals("quit"))
{
����������� break;
�������� }
�������� try
{
����������� if
(command.equals("push"))
{
�������������� if
(!kbd.hasNextDouble()) {
����������������� kbd.nextLine();
// flush
����������������� System.out.println("argument
to push must be a double");
����������������� continue;
�������������� }
�������������� sm.push(kbd.nextDouble());
����������� } else
if (command.equals("pop")) {
�������������� //
???
����������� } else if
(command.equals("top")) {
�������������� result = "" + sm.peek();
����������� } else
if (command.equals("add")) {
�������������� sm.add();
����������� } else
if (command.equals("mul")) {
�������������� //
???
����������� } else if
(command.equals("sub"))
{
�������������� //
???
����������� } else
if (command.equals("div")) {
�������������� //
???
����������� } else
{
�������������� System.out.println("unrecognized
command: " + command);
�������������� kbd.nextLine();
// flush
����������� }
�������� } catch
(Exception e) {
����������� System.out.println(e.getMessage());
����������� kbd.nextLine();
// flush
����������� continue;
�������� }
�������� System.out.println(result);
����� }
����� System.out.println("bye");
�� }
Here's a sample output:
-> push 3
done
-> push 4
done
-> top
4.0
-> push ten
argument to push must be a double
-> puch
unrecognized command: puch
done
-> add
done
-> top
7.0
-> add
stack needs at least 2 numbers
-> quit
bye