Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Modify the class Stack to include appropriate error messages if invalid conditio

ID: 3629632 • Letter: M

Question

Modify the class Stack to include appropriate error messages if invalid conditions occur. For example, trying to pop an item when the stack is empty.
Here is the Main Code:
//Week 6 - lecture: driver program (stack)

public class Main
{
public static void main(String[] args)
{
Stack s = new Stack();

System.out.println("Insertion of 10 characters in s");
for (int i = 0; i < 10; i++)
{
int x = 32 + (int)(Math.random()*95);
System.out.println(x + " --> " + (char)x);
s.push((char)x);
}

System.out.println(" Displaying and deleting elements");
for (int i = 0; i < 10; i++)
{
System.out.println("Item at the top: " + s.peek());

s.pop();
}
}
}

Here is the Stack code:
//week 6 - lecture: Stack class

public class Stack
{
public Stack()
{
size = 100;
list = new char[size];
n = 0;
}

public Stack(int s)
{
size = s;
list = new char[size];
n = 0;
}

public void push(char c)
{
list[n] = c;
n++;
}

public void pop()
{
n--;
}

public char peek()
{
return list[n-1];
}

public boolean isEmpty()
{
return n==0;
}

private char[] list;
private int size;
private int n;
}

Explanation / Answer

Usually, invalid conditions are called exceptions and writing the necessary code for that is called exception handling. But I assume what you're requested to do here is much simpler, otherwise the instructor would have told you explicitly to do exception handling.

Now, we first think of scenarios where your Stack operations can fail:

Pop: fails when stack is empty

Peek: also fails when stack is empty

Push : fails when stack is full

In your code , the stack status is indicated by "n": the current number of full slots in the stack. Now using that n, we look at each operation and differentiate the conditions for success and failure based on the current value of n: if the stack is empty then n=0 if the stack is all full then n = size right?

So, in each operation, when everything is ok, we let it do its thing as usual, otherwise, we print a message out saying that the operation can't take place because the stack is empty/full. Here we just use system.out.println() for the error messages but you can use System.err.println() which sends the error messages -in red- to the standard output stream - generally the screen.

The Peek operation is different from pop and push because it actually returns a value, rather than just increment or decrement n. So when the Stack is empty, we print out an error message but it still expects a character value to display. For the sake of simplicity, we just give it a ' ' space character as dummy character so that when it wishes to display a character from the empty stack , it gets a blank. It all works out well for everyone.

To test out the error messages, you can use the same main method, just change the size of your stack from 100 to say 9 - and you'll see that it's having issues pushing in that 10th character into the Stack and peeking/popping out a 10h character at the end.

==================================================================================

SAME main method from Main class, with a Stack initialized with a size 9 instead of the default 100

public static void main(String[] args) {
        Stack s = new Stack(9);

        System.out.println("Insertion of 10 characters in s");
        for (int i = 0; i < 10; i++) {
            int x = 32 + (int) (Math.random() * 95);
            System.out.println(x + " --> " + (char) x);
            s.push((char) x);
        }

        System.out.println(" Displaying and deleting elements");
        for (int i = 0; i < 10; i++) {
            System.out.println("Item at the top: " + s.peek());

            s.pop();
        }
    }

Modified Stack class for the operations

public class Stack {

    public Stack() {
        size = 100;
        list = new char[size];
        n = 0;
    }

    public Stack(int s) {
        size = s;
        list = new char[size];
        n = 0;
    }

    public void push(char c) {
        if(n < size)
        {
            list[n] = c;
            n++;
        }
        else
            System.out.println("Canot complete Push operation: Stack is Full.");
    }

    public void pop() {
        if( n > 0 )
            n--;
        else
            System.out.println("Cannot complete Pop operation: Stack is Empty.");
    }

    public char peek() {
        if(n > 0)
            return list[n - 1];
        else
        {
            System.out.println("Cannot complete Peek operation: Stack is Empty.");
            return ' '; // return a blank character to simulate null
        }
    }

    public boolean isEmpty() {
        return n == 0;
    }
    private char[] list;
    private int size;
    private int n;

    }

=======================================================================================

I just noticed the isEmpty() boolean method sitting there just begging to be used, that is the perfect method to use when checking for empty stack in Pop and Peek. We can also write an isFull() method to use for the Push operation, the Main remains unchanged and the resulting code for the Stack class wouls look like this:

public class Stack {

    public Stack() {
        size = 100;
        list = new char[size];
        n = 0;
    }

    public Stack(int s) {
        size = s;
        list = new char[size];
        n = 0;
    }

    public void push(char c) {
        if(isFull())
            System.out.println("Cannot complete Push operation: Stack is Full.");
        else
        {
            list[n] = c;
            n++;
        }
    }

    public void pop() {
        if(isEmpty())
            System.out.println("Cannot complete Pop operation: Stack is Empty.");
        else
            n--;
    }

    public char peek() {
        if(isEmpty())
        {
            System.out.println("Cannot complete Peek operation: Stack is Empty.");
            return ' '; // return a blank character to simulate null
        }
        else
        {
            return list[n - 1];
        }
    }

    public boolean isEmpty() {
        return n == 0;
    }
    
    public boolean isFull() {
        return n == size;
    }
    
    private char[] list;
    private int size;
    private int n;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote