|
Students are asked to complete the writing of two application programs involving stacks. The first of the two makes a deal out of reversing a list -- but it is a nice application of a stack. The second program uses a stack to perform postfix evaluation of an expression.
Demo
init:
deps-jar:
compile-single:
run-single:
Please enter a line of text:
1 2 3 4 5 6 7
7
6
5
4
3
2
1
BUILD SUCCESSFUL (total time: 20 seconds)
init:
deps-jar:
compile-single:
run-single:
Please enter a line of text:
java lisp prolog smalltalk sml
sml
smalltalk
prolog
lisp
java
BUILD SUCCESSFUL (total time: 52 seconds)
Code
/*
* ReverseApp.java
*
* Created on June 21, 2006, 5:47 AM
*/
package programs;
import datatypes.stack.*;
import datatypes.stack.sequential.*;
import java.util.*;
import java.io.*;
class ReverseApp
{
public ReverseApp() {
}
static public void main(String[] args)
{
String source = getSource();
ObjectStack stack = new ObjectStack ();
pushElements(stack,source);
popElements(stack);
}
static private String getSource()
{
System.out.println("Please enter a line of text: ");
return readLine();
}
static private void pushElements(ObjectStack stack,String source)
{
try {
// MISSING CODE: Something for you to do!!
// 1: Create a StringTokenizer instance
// with the value source as its parameter.
// 2: While there are more tokens, push them
// onto the stack
} catch ( ObjectStackOverflowException e ) {
System.exit(0);
}
}
static private void popElements(ObjectStack stack)
{
try {
// MISSING CODE: Something for you to do!!
// While the stack is not empty, perform a
// pop operation and print the element that
// was popped to the standard output stream.
} catch ( ObjectStackUnderflowException e ) {
System.exit(0);
}
}
static private String readLine()
{
String result = "";
char ch = ' ';
try {
while ( ch != '\n' ) {
result = result + ch;
ch = (char)System.in.read();
};
} catch (IOException e) {
result = "";
};
return result;
}
}