Question

In: Computer Science

Using Java A stack is a type of data collection on which things can be “pushed”...

Using Java

A stack is a type of data collection on which things can be “pushed” and “popped”. For example, a stack of plates can have a plate added (or “pushed”) onto the stack, and a plate removed (or “popped”) from the stack. Plates are pushed onto or popped off of the stack one at a time. The last plate pushed onto the stack is the first plate popped off of the stack. This type of structure is known as “LIFO” – last in, first out.

In this project, you will create a stack that will hold objects of type Person. The stack itself will be in a class named PersonStack.

When manipulating the stack, three types (or classes) of exceptions can be thrown. Each Exception class will contain two constructors, one which provides a default message for the exception, and one which takes a String as an argument and sets the exception message to that String.

The three Exception classes in this project are:

  1. StackFullException – thrown when trying to add (or “push”) an object onto the stack which already has reached its maximum size. The default exception message is

"PersonStack is full – object not added."

  1. StackEmptyException – thrown when trying to remove (or “pop”) an object from the stack when the stack is empty. The default exception message is

"PersonStack is empty – no object to return."

  1. IllegalObjectTypeException – thrown when trying to add an object to the stack that is not an instance of the correct type of object which the stack can hold. (In this project, the stack holds objects of type Person.) The default exception message is

"Object is not a Person – object not pushed."

Each class above extends Exception, so it is “checked”, and must appear inside a try-catch statement.

Next, you should define a class called PersonStack, which will implement the stack containing an array of Person objects. (Use the Person and Date classes provided on Canvas below.)

The details of this project:

  • The stack is implemented using an array with a capacity of 5 Person objects.  Initially it will be empty (contain no objects)
  • An int variable is used to point to the “next available stack position” in the array. Initialize this variable to 0, meaning that the stack is empty.
  • The class will provide a method named push(), which will take one argument, an object of type Object.
    • If the object is null, or if the object is not an instance of the Person class, then this method will throw an exception of type IllegalObjectTypeException, but the push method will not catch the exception.
    • If the stack is full, then this method will throw an exception of type StackFullException, but will not catch it.
    • Otherwise, the method will typecast the object to a Person, place the object on top of the stack (the element in the array referenced by the “next available stack position” variable), and increment that variable.
  • The class will provide a method named pop():
    • If the stack is empty, this method will throw an exception of type StackEmptyException, but will not catch it
    • Otherwise, the method will decrement the variable referencing the “next available stack position”, remove the Person object currently occupying that position from the stack (array), and return the Person object that was just removed from the stack.
  • The class will provide a method named toString(), which lists all of the Person objects currently residing on the stack.
  • You do not need to include an equals method for the PersonStack class

Finally, you will need to write a main “tester” program. (Please put this method in its own class, not with PersonStack.) This program will:

  • Instantiate an object of the PersonStack class – aka the “stack”.
  • Inside a “try” block:
    1. Instantiate and “push” 5 different Person objects onto the stack.  
    2. Print the contents of the stack (use the stack’s toString method).
    3. Attempt to “push” a 6thPerson object onto a stack, which should throw a StackFullException.
  • Inside a second “try” block
    1. “Pop” five Person objects from the stack. As each is “popped”, print a message showing which Person object was returned.
    2. The stack should now be empty. Try to “pop” a 6th object from the stack, which should throw a StackEmptyException.
  • In a third “try” block:
    1. Instantiate an object of any type other than Person. (For example, you could use a Date or a String)
    2. Try to “push” this object onto the stack. This should throw an IllegalObjectTypeException
  • After each “try” block above, you will need to add “catch” blocks to handle the types of exceptions which can be thrown by methods inside the “try” block, because those methods do not handle the exceptions themselves.
    1. The “push” method can throw a StackFullException and an IllegalObjectTypeException.
    2. The “pop” method can throw a StackEmptyException.

In each “catch” block, print the exception message, but do not stop.

Please do not change the Person or Date classes.  

A sample dialog might look like:

  Just added five people onto the stack
  Here are the contents of the stack: 
     Name: Harry Potter  born: July 31, 1997
     Name: Beyoncé  born: September 4, 1981
     Name: James T. Kirk  born: March 22, 2233
     Name: Tom Brady  born: June 1, 1989
     Name: Oprah Winfrey  born: March 25, 1975
  Trying to push one more onto the stack:
  PersonStack is full - object not added

  Popping the contents of the stack plus one.
     Popped: Name: Oprah Winfrey  born: March 25, 1975  
     Popped: Name: Tom Brady  born: June 1, 1989
     Popped: Name: James T. Kirk  born: March 22, 2233
     Popped: Name: Beyoncé  born: September 4, 1981
     Popped: Name: Harry Potter  born: July 31, 1997
  PersonStack is empty - no object to return
 
  Trying to add an Object object to the stack. 
  Object not a Person - object not pushed

Solutions

Expert Solution

//first solution

class Person
{
   String name,dob;
   Person(String name,String dob)
   {this.name=name;
   this.dob=dob;
   }
}
class IllegalObjectTypeException extends Exception{
   IllegalObjectTypeException()
   {super("default message");
   }
   IllegalObjectTypeException(String s){
   super(s);
   }
}
class StackFullException extends Exception{
   StackFullException()
   { super("default message");
   }
   StackFullException(String s){
   super(s);
    }
}
class StackEmptyException extends Exception{
   StackEmptyException(){
   super("default message");
    }   
   StackEmptyException(String s){
   super(s);
    }
}   

class PersonStack
{
   int capacity=5;
   Person p[]=new Person[capacity];
   int top=0;
   public void push(Object obj) throws Exception
   {
       if(obj==null||obj instanceof Person==false)
       throw new IllegalObjectTypeException("Object not a Person - object not pushed");
       else if(top>=capacity)
       throw new StackFullException("PersonStack is full - object not added");
       else
       p[top++]=(Person)obj;

   }
   public Person pop() throws Exception
   {
       if(top<=0)
       throw new StackEmptyException("PersonStack is empty - no object to return");
       else
       {
           return p[--top];
       }
      
   }
   public String toString()
   {String s=" Here are the contents of the stack: \n";
       for(int i=0;i<top;i++)
       {
           s+="Name: "+p[i].name+" born: "+p[i].dob+"\n";
       }
       return s;
   }

}
class Tester
{
   public static void main(String arg[])
   {
   PersonStack ps=new PersonStack();
   try
   {
       System.out.println("Popping the contents of the stack plus one.");
       Person p1=new Person("Harry Potter","July 31, 1997");
       ps.push(p1);
       Person p2=new Person("Beyoncé","September 4, 1981");
       ps.push(p2);
       Person p3=new Person("James T. Kirk ","March 22, 2233");
       ps.push(p3);
       Person p4=new Person("Tom Brady","June 1, 1989");
       ps.push(p4);
       Person p5=new Person("Oprah Winfrey","March 25, 1975");  
       ps.push(p5);
       System.out.println(ps.toString());
       Person p6=new Person("Harry Potter","July 31, 1997");
       ps.push(p6);
          
   }
  
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }
  
   try
   {Person p=ps.pop();
       System.out.println("Popping the contents of the stack plus one.");
       System.out.println("Name: "+p.name+" born: "+p.dob);
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob);
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob);
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob);
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob);
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob);
  

          
   }
  
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }
   try
   {
   String s="Apple";
   ps.push(s);
  
   }
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }

      
   }
}

//if you want Date class Then Second solution

class Date
{
   int day,year;
   String month;
   Date(int day,String month,int year)
   {this.day=day;
   this.month=month;
   this.year=year;
   }
   public String toString()
   {String s="";
   s+=this.month+" "+this.day+", "+this.year;
       return s;
   }
}
class Person
{
   String name;
   Date dob;
   Person(String name,Date dob)
   {this.name=name;
   this.dob=dob;
   }
}
class IllegalObjectTypeException extends Exception{
   IllegalObjectTypeException()
   {super("default message");
   }
   IllegalObjectTypeException(String s){
   super(s);
   }
}
class StackFullException extends Exception{
   StackFullException()
   { super("default message");
   }
   StackFullException(String s){
   super(s);
    }
}
class StackEmptyException extends Exception{
   StackEmptyException(){
   super("default message");
    }   
   StackEmptyException(String s){
   super(s);
    }
}   

class PersonStack
{
   int capacity=5;
   Person p[]=new Person[capacity];
   int top=0;
   public void push(Object obj) throws Exception
   {
       if(obj==null||obj instanceof Person==false)
       throw new IllegalObjectTypeException("Object not a Person - object not pushed");
       else if(top>=capacity)
       throw new StackFullException("PersonStack is full - object not added");
       else
       p[top++]=(Person)obj;

   }
   public Person pop() throws Exception
   {
       if(top<=0)
       throw new StackEmptyException("PersonStack is empty - no object to return");
       else
       {
           return p[--top];
       }
      
   }
   public String toString()
   {String s=" Here are the contents of the stack: \n";
       for(int i=0;i<top;i++)
       {
           s+="Name: "+p[i].name+" born: "+p[i].dob.toString()+"\n";
       }
       return s;
   }

}
class Tester
{
   public static void main(String arg[])
   {
   PersonStack ps=new PersonStack();
   try
   {
       System.out.println("Popping the contents of the stack plus one.");
       Date dob=new Date(31,"July",1997);
       Person p1=new Person("Harry Potter",dob);
       ps.push(p1);
       dob=new Date(4,"September",1981);
       Person p2=new Person("Beyoncé",dob);
       ps.push(p2);
       dob=new Date(22,"March",2233);
       Person p3=new Person("James T. Kirk ",dob);
       ps.push(p3);
       dob=new Date(1,"June",1989);
       Person p4=new Person("Tom Brady",dob);
       ps.push(p4);
       dob=new Date(25,"March",1975);
       Person p5=new Person("Oprah Winfrey",dob);  
       ps.push(p5);
       System.out.println(ps.toString());
       dob=new Date(31,"July",1997);
       Person p6=new Person("Harry Potter",dob);
       ps.push(p6);
          
   }
  
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }
  
   try
   {Person p=ps.pop();
       System.out.println("Popping the contents of the stack plus one.");
       System.out.println("Name: "+p.name+" born: "+p.dob.toString());
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob.toString());
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob.toString());
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob.toString());
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob.toString());
       p=ps.pop();
       System.out.println("Name: "+p.name+" born: "+p.dob.toString());
  

          
   }
  
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }
   try
   {
   String s="Apple";
   ps.push(s);
  
   }
   catch(Exception e)
   {
       System.out.println(e.getMessage());
   }

      
   }
}


Related Solutions

Using existing Stack Java Collection Framework, write Java Code segment to do the following.   You may...
Using existing Stack Java Collection Framework, write Java Code segment to do the following.   You may write this in jGrasp Create a Stack of String called, myStacks Read input from keyboard, 10 names and then add to myStacks As you remove each name out, you will print the name in uppercase along with a number of characters the name has in parenthesis. (one name per line).   e.g.     Kennedy (7) Using existing Stack Java Collection Framework, write Java Code segment to...
Java program Reverse polish notation: using stack - You can use the Stack included in java.util.Stack...
Java program Reverse polish notation: using stack - You can use the Stack included in java.util.Stack (or your own implementation) for this problem. Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free. Write a program which...
Introduced to data structure using java 2)One of the applications of stack is to convert infix...
Introduced to data structure using java 2)One of the applications of stack is to convert infix expressions to postfix. Given the following infix expression, use the stack method to convert it to postfix. Show your work. x - y / (a + b) + z 3)write a generic method to find the maximum of three variables of generic type (i.e. type T). Note that you must use the compareTo method to compare the values. Also, the code must return one...
In Java or C++, implement a stack and a queue using a linkedlist data structure.  You may...
In Java or C++, implement a stack and a queue using a linkedlist data structure.  You may not use any standard Java or C++ libraries. Assume your data structure only allows Strings. Implement the following operations for the data structure: Queue: enqueue, dequeue, create, isEmpty (10 points) Stack: push, pop, create, isEmpty (10 points) Here is a link to get started on transferring from Java to C++ http://www.horstmann.com/ccj2/ccjapp3.html (Links to an external site.) Upload a zip file with one implementation for...
Explain how the reference count garbage collection works? Which limitation is removed using TBD stack and...
Explain how the reference count garbage collection works? Which limitation is removed using TBD stack and how? [25 points]
1. Implement the stack abstract data type. Write it as a separate class called Stack. For...
1. Implement the stack abstract data type. Write it as a separate class called Stack. For simplicity the data type to be stored in the stack is String but you can also use generic type. 2. Test your class implementation by calling push() and pop(). If the stack is empty (size equals zero) pop() should return null and print that “stack is empty”. If stack is full (size equals max) push() returns false and prints that “stack is full”. This...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class Stack{ public Stack(){ // use LinkedList class } public void push(int item){ // push item to stack } public int pop(){ // remove & return top item in Stack } public int peek(){ // return top item in Stack without removing it } public boolean isEmpty(){ // return true if the Stack is empty, otherwise false } public int getElementCount(){ // return current number...
0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that...
Learning Outcomes Using Java, maintain a collection of objects using an array. Construct a class that contains an array as a private instance variable. Construct methods with arrays as parameters and return values. Use partially filled arrays to implement a class where objects can be dynamically added. Implement searching and sorting algorithms. Instructions For this assignment you will be implementing an application that manages a music collection. The application will allow the user to add albums to the collection and...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a class for a Queue of characters using a linked list implementation. Write a class for a Queue of integers using a circular array implementation.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT