Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Your will write your code in StackArray.java, which is an array based implementation of a stack. The StackArray class has 2 private fields that you

Your will write your code in StackArray.java, which is an array based implementation of a stack. The StackArray class has 2 private fields that you can directly access in your code: private int[] stack; private int top; stack is an array of integers that will store the stack values. top is an index to the current top of the stack. A top value of -1, which is an invalid index, is used to indicate when the stack is empty. StackArray provides 2 public accessor functions for other classes to get the values of these private fields. Stack top --------- The top of a stack refers to an occupied place, not an empty place. Consider, for example, a stack of plates. If the stack of plates is not empty, a plate is at its top. Refer to figure 14.11a for an example. When you add (put) an item on a stack, you must first increment its top index. When you remove (pop) an item from a stack, you must decrement its top index. If the stack becomes empty, you must set the top index to -1. Part 1 (push) ------------- The framework comments say: "The push method adds the argument value to the top of the stack, if it is possible" Remember that "argument value" is just another way to say "parameter value". For the "push" function, the parameter here is named "value" and it is an int. What do they mean by "if it is possible"? They mean as long as there is still room to add another item. Understand that they told us that this stack has a limited capacity. The framework comments say: "CAPACITY is a constant instance variable representing the size of the array stack" The first thing you must do is make sure there is room for another item. You must compare "top" to "CAPACITY" in some way that understands that top is a 0-relative index into the stack array and CAPACITY is the size (max number of items allowed in this array). If top is already at the limit level, you must display the following message to the system console: "Stack is full: cannot push " + value and then return false, which takes your flow out of the function. BELOW your if block, you know you have room to add the new item to the stack because the flow would not continue there if it took the return false path. You need to add a new item and you know you have room in the stack array. Change the top index to the next available array slot. Use this new value of top to assign the new item to this array slot. The new item is passed into the push function as the parameter "value". After you add the value via an assignment statement, remember that your function must return a boolean (true or false). Since you added an item at this point, you return true. Part 2 (pop) ------------ The best place to start with any function is to examine how it is declared. What are its parameters? What is its return type? Does it throw any exceptions? You can see that the pop() function takes no parameters and returns an int value. You can also see that it might throw a DataStructureException exception (if it encounters a certain situation). Let's start by asking when your code will need to throw the exception. The purpose of the pop function is to return the top item on the stack. If the stack is currently empty, then this cannot be done. The first thing you will check is if the stack is empty, which is indicated by a top value of -1. If the stack is empty you must throw the exception. This exception should be instantiated with the following message text: "Stack is empty: cannot pop" When you throw an exception, that takes you out of the flow right then and there, so there is no need to have any return statement after the throw statement. Review the section on exceptions to see how to throw the exception. BELOW the above "if" block, you know that the stack is not empty. You could not possibly reach that place in your code if your stack was empty because your thrown exception would have taken you out of the pop function. What do you need to do next? First, you need to get the top item into an int local variable. You do this by using the "top" index into the "stack" array. Next, you must adjust the "top" index to make it refer to a new top item. This new top is obviously the item underneath (below) the current top. You must have first obtained the current top item before you change the top index. After adjusting the top index, return the item you obtained, which was saved in the local variable mentioned above. Comments -------- The source code method header comments contain important information about what the method is supposed to do and what it is supposed to return.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* The DataStructureException class
 Anderson, Franceschi
*/
 
public class DataStructureException extends Exception
{
 public DataStructureException( String s )
 {
 super( s );
 }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* StackArray * Anderson, Franceschi */ import java.awt.Graphics; import javax.swing.JFrame; import java.awt.Color; public class StackArray { public static final int CAPACITY = 10; private int[] stack; private int top; public StackArray() { stack = new int[CAPACITY]; top = -1; } public int get(int index) { return stack[index]; } public int getTop() { return top; } /** * push method * * @param value value to be pushed onto the stack * @return true if successful, false if unsuccessful */ public boolean push(int value) { // ***** 1. Student code starts here ***** // stack is an int array instance variable representing // the array that stores our stack // top is an instance variable representing // the index of the top of the stack // CAPACITY is a constant instance variable representing // the size of the array stack // The push method adds the argument value // to the top of the stack, if it is possible // code the push method here // Part 1 student code starts here: return true; // replace this dummy return statement // Part 1 student code ends here. } /** * pop method * * @return the value of the top element of the stack, if successful */ public int pop() throws DataStructureException { // ***** 2. Student code restarts here ***** // stack is an int array instance variable representing // the array that stores our stack // top is an instance variable representing // the index of the top of the stack // CAPACITY is a constant instance variable representing // the size of the array stack // The pop method deletes the element // at the top of the stack, if it is possible // Code the pop method here // Part 2 student code starts here: return 0; // replace this dummy return statement // Part 2 student code ends here. } } 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* StackArrayDrawing * Anderson, Franceschi */ import java.awt.Graphics; import javax.swing.JFrame; import java.awt.Color; public class StackArrayDrawing { public static final int XSTART = 200; public static final int YSTART = 300; public static final int WIDTH = 100; public static final int HEIGHT = 25; private StackArray sa; private boolean pushSuccess; private boolean popSuccess; private int pushedValue; private int poppedValue; private boolean operation; // true for push, false for pop private String description = ""; private boolean started; public StackArrayDrawing( ) { sa = new StackArray( ); } public void setPushSuccess( boolean newPushSuccess ) { started = true; pushSuccess = newPushSuccess; } public void setPopSuccess( boolean newPopSuccess ) { popSuccess = newPopSuccess; } public void setPushedValue( int newPushedValue ) { pushedValue = newPushedValue; } public void setPoppedValue( int newPoppedValue ) { poppedValue = newPoppedValue; } public void setOperation( boolean newOperation ) { operation = newOperation; } public void setStarted( boolean newStarted ) { started = newStarted; } public boolean push( int value ) { return ( sa.push( value ) ); } public int pop( ) throws DataStructureException { return( sa.pop( ) ); } public void draw( Graphics g ) { // draw the empty stack and indices g.setColor( Color.BLUE ); drawEmptyStack( g ); // draw the stack contents g.setColor( Color.RED ); drawStackContents( g ); // draw top g.setColor( Color.BLACK ); drawTop( g ); // determine operation if ( operation ) // push { if ( pushSuccess ) { description = "successfully pushed " + pushedValue; } else { description = "failed to push " + pushedValue; } } else // pop { if ( popSuccess ) { description = "successfully popped " + poppedValue; } else { description = "failed to pop"; } } if ( !started ) description = ""; drawDescription( g ); } public void drawEmptyStack( Graphics g ) { for ( int i = 0; i < StackArray.CAPACITY; i++ ) { g.drawRect( XSTART, YSTART - i * HEIGHT, WIDTH, HEIGHT ); g.drawString( "" + i, XSTART - WIDTH / 4, (int) ( YSTART - ( i - 0.7 ) * HEIGHT ) ); } } public void drawStackContents( Graphics g ) { int i = 0; g.setColor( Color.BLACK ); for ( i = 0; i <= sa.getTop( ); i++ ) { g.drawString( "" + sa.get( i ), XSTART + WIDTH / 2 - 5, (int) ( YSTART - ( i - 0.7 ) * HEIGHT ) ); } g.setColor( Color.RED ); for ( i = sa.getTop( ) + 1; i < StackArray.CAPACITY; i++ ) { g.drawString( "" + sa.get( i ), XSTART + WIDTH / 2 - 5, (int) ( YSTART - ( i - 0.7 ) * HEIGHT ) ); } } public void drawTop( Graphics g ) { g.drawString( "top", XSTART - WIDTH / 2, (int) ( YSTART - ( sa.getTop( ) - 0.7 ) * HEIGHT ) ); } public void drawDescription( Graphics g ) { g.drawString( description, XSTART + WIDTH + 20, YSTART / 2 ); } } 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* StackPractice * Anderson, Franceschi */ import java.awt.*; import javax.swing.*; import java.awt.event.*; public class StackPractice extends JFrame { Container contents; // GUI components private JButton push; private JButton pop; private ButtonHandler bh; private StackArrayDrawing sad; private static StackPractice app; private boolean firstTime = true; public StackPractice( ) { super( "Push or pop" ); contents = getContentPane( ); contents.setLayout( new FlowLayout( ) ); sad = new StackArrayDrawing( ); push = new JButton( "push" ); contents.add( push ); pop = new JButton( "pop" ); contents.add( pop ); bh = new ButtonHandler( ); push.addActionListener( bh ); pop.addActionListener( bh ); setSize( 500,400 ); setVisible( true ); } private void animate( boolean pushSuccess, int pushedValue ) { sad.setPushSuccess( pushSuccess ); sad.setPushedValue( pushedValue ); try { repaint( ); Thread.sleep( 200 ); } catch ( InterruptedException e ) { System.out.println( "IE Exception " + e.getMessage( ) ); System.out.println( e.toString( ) ); } } private void animate( int poppedValue ) { sad.setPopSuccess( true ); sad.setPoppedValue( poppedValue ); try { repaint( ); Thread.sleep( 200 ); } catch ( InterruptedException e ) { System.out.println( "IE Exception " + e.getMessage( ) ); System.out.println( e.toString( ) ); } } private void animate( ) { sad.setPopSuccess( false ); try { repaint( ); Thread.sleep( 200 ); } catch ( InterruptedException e ) { System.out.println( "IE Exception " + e.getMessage( ) ); System.out.println( e.toString( ) ); } } public void paint( Graphics g ) { if ( firstTime ) firstTime = false; super.paint( g ); sad.draw( g ); } public static void main( String [] args ) { app = new StackPractice( ); app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } private class ButtonHandler implements ActionListener { private boolean success = false; public void actionPerformed( ActionEvent e ) { sad.setStarted( true ); if ( e.getSource( ) == push ) { sad.setOperation( true ); int insertValue = getValue( ); success = sad.push( insertValue ); animate( success, insertValue ); } else // ( e.getSource( ) == pop ) { sad.setOperation( false ); try { int popped = sad.pop( ); animate( popped ); } catch( DataStructureException dse ) { System.out.println( dse.getMessage( ) ); animate( ); } } } } public int getValue( ) { int value = 0; boolean goodInput = false; while ( !goodInput ) { try { String answer = JOptionPane.showInputDialog ( null, "Enter an integer value" ); value = Integer.parseInt( answer ); goodInput = true; } catch( Exception e ) { } } return value; } } 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database And Expert Systems Applications 23rd International Conference Dexa 2012 Vienna Austria September 2012 Proceedings Part 1 Lncs 7446

Authors: Stephen W. Liddle ,Klaus-Dieter Schewe ,A Min Tjoa ,Xiaofang Zhou

2012th Edition

3642325998, 978-3642325991

More Books

Students also viewed these Databases questions

Question

13.5 Multicollinearity

Answered: 1 week ago