Java Reference
In-Depth Information
Like
ArrayList
operations, the
Stack
operations operate on
Object
references.
Because all objects are derived from the
Object
class, any object can be pushed
onto a stack. If primitive types are to be stored, they must be treated as objects
using the corresponding wrapper class. Unlike the
Stack
class, no class imple-
menting a queue is defined in the Java API.
Let's look at an example that uses a stack to solve a problem. The program in
Listing 13.4 accepts a string of characters that represents a secret message. The
program decodes and prints the message.
LISTING 13.4
//********************************************************************
// Decode.java Author: Lewis/Loftus
//
// Demonstrates the use of the Stack class.
//********************************************************************
import
java.util.*;
public class
Decode
{
//-----------------------------------------------------------------
// Decodes a message by reversing each word in a string.
//-----------------------------------------------------------------
public static void
main (String[] args)
{
Scanner scan =
new
Scanner (System.in);
Stack word =
new
Stack();
String message;
int
index = 0;
System.out.println ("Enter the coded message:");
message = scan.nextLine();
System.out.println ("The decoded message is:");
while
(index < message.length())
{
// Push word onto stack
while
(index < message.length() && message.charAt(index) != ' ')
{
word.push (
new
Character(message.charAt(index)));
index++;
}
Search WWH ::
Custom Search