how to check when stack is empty - java

well this is my array stack separated from my main
i have just one problem though, my code have no problems yet it lacks
something like if i run pop yet the stack is empty, it must have a dialog saying that it is empty, i tried an if else statement yet i dont know where to put it or is it really the if else statement needed, anyways here's my code. . .
public class ArrayStack {
int STACK_MAX = 20;
int size = -1 ;
int top = -1 ;
int StackObj[] = new int[STACK_MAX];
/**************** for PUSH METHOD *********/
public void Push(int obj) {
if (size()==STACK_MAX){
System.out.println("STACK is FULL");
}
else{
StackObj[++top]= obj;
}
}
/**************** for SIZE Method ********/
public int size() {
return (top+1);
}
/******************** for Display Method****/
public void DisplayStack() {
String disp="";
for (int i=top; i>=0; i--){
disp += StackObj[i] + "\n";
}
JOptionPane.showMessageDialog(null, "Elements of the Stacks : \n" + disp);
}
/***************** for isEmpty Method *******/
public boolean isEmpty(){
return (top == -1);
}
/***************** for Top Method ***********/
public int Topmethod(){
int taas = StackObj[top];
JOptionPane.showMessageDialog(null,"Top is : "+taas);
return (top);
}
/***************** for Pop Method ***********/
public int pop(){
int topItem = StackObj[top];
top--;
JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem);
return(top);
}
}

You would want to add something in your pop method to handle recognizing when the stack was empty then handling the case of an empty stack such as:
public int pop(){
if(size() == 0){ //detect empty stack
JFrame frame = new JFrame("my frame");; //handle empty stack
JOptionPane.showMessageDialog(frame,"Stack is empty!");
return null; //make sure you handle a null return value if you use this
}
int topItem = StackObj[top];
top--;
JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem);
return(top);
}

here i edited it
public int pop(){
if(size() == 0){ //detect empty stack
JOptionPane.showMessageDialog(null,"Stack is empty!");
return (top); //make sure you handle a null return value if you use this
}
int topItem = StackObj[top];
top--;
JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem);
return(top);
}

Related

How do I create a Print Method that is called in the Main method that prints an array in reverse?

Im working with stacks as an assignment and I am able to do the generic pop, push, and peek as required. I am not able to print however? The professor I am working with is doing things differently from how I was taught in my last class, so I am not sure how to go about what he wants. I have tried asking him but it usually ends in me being more confused and him sounding condescending because I did not take his class and did not learn what exactly his other students did. I have a series of methods to manipulate the char stack. I am supposed to call pop, peek, and push from the main method to add and view it. The professor also wants a print method however but I am unsure of how to do it. Here is what I have so far;
public class StackChar {
//data
private static int size;
private static int top;
private static char[] data;
public StackChar() {
}
public StackChar(int sz) {
size = sz;
top = -1;
data = new char[size];
}
/**
* Description: This method will push an item onto the top of the stack
*/
public void push(char letter) {
if (top != size - 1) {
top += 1;
data[top] = letter;
} else {
System.out.println("Error: Stack Is Full");
}
}
public char pop() {
char let1;
if (top >= 0) {
let1 = data[top];
top--;
return (let1);
}
System.out.println("Error: Stack Is Empty");
return (char)-1;
}
public char peek() {
char let1;
if (top >= 0) {
let1 = data[top];
return (let1);
}
System.out.println("Error: Stack Is Empty");
return (char)-1;
}
public static void prints(char[] sc) {
if (top == -1) {
System.out.println("Error: Stack Is Empty");
return;
}
for (int i = size - 1; i > -1; i--) {
System.out.println(letterStack[i]);
}
}
public static void main(String[] args) {
StackChar sc = new StackChar(10);
//after each stack method push, pop, peek, you will use prints().
sc.push('a');
sc.push('b');
sc.push('c');
prints(sc);
sc.prints();
//push 6 a-f letters of alphabet in normal order
//THEN
//push the next letter of alphabet
//THEN
//pop 1
//push the next letter of the alphabet
//pop 2
//push the next letter of the alphabet
//pop 3
//peek and print what the peek gives
}
}
My problem lies in the print method, and calling the print method from the Main method. I am used to simply calling the method on whatever I need it on; sc.print() for example. This does not seem to want to work and I am not sure why. I also tried changing the print method so that it took the stack as an argument and calling the print method and putting the array into it, but that didnt seem to work either.
public final class StackChar {
private int top = -1;
private final char[] data;
public StackChar(int size) {
data = new char[size];
}
public int getSize() {
return top + 1;
}
public void push(char ch) {
requireNotFull();
data[++top] = ch;
}
public char pop() {
requireNotEmpty();
return data[top--];
}
public char element() {
requireNotEmpty();
return data[top];
}
private void requireNotFull() {
if (top == data.length - 1)
throw new RuntimeException("Stack Is Full");
}
private void requireNotEmpty() {
if (top == -1)
throw new RuntimeException("Stack Is Empty");
}
public static void print(StackChar stack) {
System.out.print('[');
for (int i = 0; i <= stack.top; i++) {
if (i > 0)
System.out.print(',');
System.out.print(stack.data[i]);
}
System.out.println(']');
}
public static void main(String... args) {
StackChar stack = new StackChar(10);
stack.push('a');
stack.push('b');
stack.push('c');
print(stack); // [a,b,c]
stack.push('a');
stack.push('b');
stack.push('c');
stack.push('d');
stack.push('e');
stack.push('f');
print(stack); // [a,b,c,a,b,c,d,e,f]
stack.push('g');
print(stack); // [a,b,c,a,b,c,d,e,f,g]
stack.pop(); // g
print(stack); // [a,b,c,a,b,c,d,e,f]
stack.push('h');
print(stack); // [a,b,c,a,b,c,d,e,f,h]
stack.pop(); // h
stack.pop(); // f
print(stack); // [a,b,c,a,b,c,d,e]
stack.pop(); // e
stack.pop(); // d
stack.pop(); // c
print(stack); // [a,b,c,a,b]
}
}

How do i implement the push pop peek methods for an inverse array?

Create a class called inverse_Stack where our 'stack' is organized in such a way where the first/"bottom" element is located at index (-1). Each element pushed is placed into the array slot before the [current] top-most element. if(size=0)store at index: (length -1); if(size=1), store at index:(length -2);if(size=2), store at index: (length-3);
This is all i have so far. Lost with the push pop peek methods for an inverse stack. I know how to make them work for a regular stack
public class Inverse_Stack<T> implements StackADT<T>{
private T[] stack;
private int top;
//private int bot;
public Inverse_Stack(){
this(100);
}
public Inverse_Stack(int capacity){
top = 0;
stack = (T[] new Object[capacity];
}
public int size(){
//returns size of array
return stack.length;
}
public void push(T element){
//fill in code
}
private void expandCapacity(){
T[] newStack = (T[] new Object[stack.length*2];
for(int i = 0; i < stack.length;i++)
newStack[i] = stack[i];
stack = newStack;
}
public T pop(){
if(isEmpty())
throw new RuntimeException("Empty Stack");
//fill in code
}
public T peek(){
if(isEmpty())
throw new RuntimeException("Empty Stack");
//fill in code
}
length tells you the capacity: the number of items the stack can hold. You also need to keep a count variable so you know how many items are currently in the stack.
I won't write the Java code, but I can give you the general idea:
In your constructor, set count to 0.
isEmpty returns true if count is greater than 0.
push
if the stack is full, expand the capacity
add element at stack[count]
increment count
pop
if the stack is empty, throw empty stack exception
decrement count
return the value at stack[count]
peek is like pop, but you don't actually decrement count.
Is not ArrayDeque doing exactly what you want?
public class InverseStack<T> extends ArrayDeque<T> {
…
}
and toArray( T[] a ) would get Your inverse array
this is my answer. I think this is more help you.
class StackX {
private int maxSize; //size of stack array
private char[] stackData;
private int top; //top of stack
//-------------------------------------------------------------------------
public StackX(int s) {
this.stackData = new char[s];
this.maxSize = s;
this.top = -1;
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
public void push(char item) {
if (isFull()) {
System.out.println("Stack is full");
return;
}
stackData[++top] = item;
}
public char pop() throws Exception {
if (isEmpty()) {
throw new Exception("Stack is empty");
}
return stackData[top--];
}
public char peek() throws Exception {
if (isEmpty()) {
throw new Exception("Stack is empty");
}
char peekValue = this.pop();
this.push(peekValue);
return peekValue;
}
public void display() {
if (isEmpty()) {
System.out.println("Stack is empry");
}
System.out.println("Start printing stack data");
for (int i = top; i >= 0; i--) {
System.out.println(stackData[i]);
}
System.out.println("End printing stack data");
}
}

What is the problem with my code , I am trying to search in the stack with an internall and external method

Write a method to find the position of a given element in a stack counting from the top of the stack. More precisely,
the method should return 0 if the element occurs on the top, 1 if there is another element on top of it, and so on. If
the element occurs several times, the topmost position should be returned. If the element doesn’t occur at all, -1
must be returned.
You are asked to write this method in two different ways; one way is to implement it internally inside the
ArrayStack class and the other way is to implement it externally in a separate class. Important: At the end
the stack should be returned to the original state (i.e. no elements should be removed and the order of the elements
should not change).
This is the externall class
public class Stack{
public static int searchstack(ArrayStack z, int n) {
ArrayStack temp = new ArrayStack(z.size());
int c = 0;
boolean flag = false;
while (!z.isEmpty()) {
if (z.top() == n) {
flag = true;
return c;
}
if (z.top() != n) {
temp.push(z.pop());
c++;
flag = false;
}
}
if (flag == false) {
c = -1;
}
while (!temp.isEmpty() && !z.isFull()) {
z.push(temp.pop());
}
return c;
}
public static void main(String[] args) {
ArrayStack z = new ArrayStack(4);
z.push(3); // first element
z.push(7);// 2nd
z.push(8);// 3rd
z.push(1);// 4th
z.printStack();
int n = 3;
System.out.println("Searching externally for" + " " + n + " " + searchstack(z, n));
System.out.println("Searching internally for" +" "+n+" "+ z.searchfor(n)+" "); //THE ERROR IS HERE
}
}
And this is the ArrayClass
public class ArrayStack {
private int[] theStack;
private int maxSize;
private int top;
public ArrayStack(int s) {
maxSize = s;
theStack = new int[maxSize];
top = -1;
}
public void push(int elem) {
top++;
theStack[top] = elem;
}
public int pop() {
int result = theStack[top];
top--;
return result;
}
public int top() {
return theStack[top];
}
public boolean isFull() {
return (top == (maxSize - 1));
}
public boolean isEmpty() {
return (top == -1);
}
public int size() {
return (top + 1);
}
//HERE IS THE METHOD I IMPLEMENTED INTERNALLY AND CALL IT AT THE STACK CLASS
public int searchfor(int n) {
for (int i = top; i >= 0; i--) {
if (theStack[top] == n) {
return i;
}
}
return -1;
}
public void printStack() {
if (top == -1)
System.out.println("Stack is empty!!\n");
else {
System.out.println(theStack[top] + " <- top");
for (int i = top - 1; i >= 0; i--)
System.out.println(theStack[i]);
System.out.println();
}
}
}
The error appearing at the Stack class is at the last line of calling the searchfor method implemented in the Arraystack class , error says that there is no method implemented in Arraystack with the name searchfor (); thiugh I did implement it .whatseems to be the problem ?
You have a bug in your searchStack() implementation. You are losing elements if you find the one you are looking for and it isn't the topmost one.
How to fix your searchStack() method:
keep popping z until you have an empty ArrayStack. While doing so, add the value to a queue.
create valIndex and assign it -1.
Then go through the queue and remove the items from it and adding them to z. While doing so, check for the last occurence of the desired value and save it in valIndex.
if valIndex equals -1 return it. Else, use following equation to convert it to correct index and return:
valIndex = (z.size - 1) - valIndex

Java Set array to full

public static void addItem()
{
boolean items = false;
System.out.println("Enter item name");
item = sc.nextLine();
while (item.equalsIgnoreCase("")) {
item = "unknown";
}
System.out.println("Enter item type");
itemType = sc.nextLine();
while (!itemType.equalsIgnoreCase("yes")
&& !itemType.equalsIgnoreCase("no")
&& !itemType.equalsIgnoreCase(null)) {
System.out.println("Please enter yes or no only");
itemType = sc.nextLine();
}
if (itemType.equalsIgnoreCase("yes"))
items = true;
else if (itemType.equalsIgnoreCase("no"))
items = false;
if (itemList.addItem(new Item(item, itemType)))
System.out.println("Item added successfully\n");
else
System.out.println("Shop is full\n");
}
My itemList class
public boolean addItem(Item anItem)
{
// if the array is full, return false
// if the array is not full, add the item to the array and
// increment counter
if (count == items.length) {
return false;
} else {
items[count] = anItem;
count++;
return true;
}
}
What are the possible ways for me to add System.out.println("Shop is full") at the start whenever my array is full and new data can be added when my array is not full?
What I have tried was the shop is full will be displayed in the end whenever my array is full, however, I want it to be displayed in the beginning instead of in the end. Any help here?
You can define an isFull() method in itemList class, and call that method where ever you want. This way you can find out if the list is full before trying to add a new item to it.
public boolean isFull()
{
return (count == items.length);
}
Not sure I understand your code entirely, but you can add the following method in your itemList class (btw, classes should be named with capital, like ItemList):
public boolean isFull(){
return count == items.length;
}
and then in your original code you can just do
if(itemList.isFull()){
System.out.println("Shop is full");
}
else{
\\rest of code here
}
in your itemlist class add the following method to check for empty spaces;
public boolean checkSpaces() {
boolean x = true;
if (this.count == items.length || this.count > items.length) { return false; }
return x;
}
then at the beginning check for empty spaces
I would think you could add System.out.println(Shop is full) right before you return false in your if statement.
public boolean addItem(Item anItem)
{ // if the array is full, return false
// if the array is not full, add the item to the array and
// increment counter
if (count == items.length){
System.out.println(Shop is full)
return false;
}
else{
items[count] = anItem;
count ++;
return true;
}
}

Beginner Stacks, OutofBoundsException Java

Hey I have a question as to why my program is throwing an ArrayIndextOutofBounds Exception
I've looked everywhere on the internet and have gone through the code but I know I'm missing something.
This is my first program that has implemented stacks and to be quite frank I'm not exactly 100% on what it is I am doing.
I think the problem is coming from my isEmpty method but can't exactly see what I am doing wrong.. there must be an easier way to test if a stack is empty or not?
Any help would be greatly appreciated.
PS: am I setting up my test stack correctly?
Heres my code:
import java.util.Arrays;
public class ArrayStack<T> implements StackADT<T>
{
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
private int emptyCount = 0;
//Creates an empty stack using the default capacity.
public ArrayStack()
{
this(DEFAULT_CAPACITY);
}
//Creates an empty stack using the specified capacity.
#SuppressWarnings("unchecked")
public ArrayStack(int initialCapacity)
{
top = 0;
stack = (T[])(new Object[initialCapacity]);
}
/* Adds the specified element to the top of this stack, expanding
the capacity of the array if necessary.*/
public void push(T element)
{
if (size() == stack.length)
expandCapacity();
stack[top] = element;
top++;
}
/*Creates a new array to store the contents of this stack with
twice the capacity of the old one.*/
private void expandCapacity()
{
stack = Arrays.copyOf(stack, stack.length * 2);
}
/*Removes the element at the top of this stack and returns a
reference to it.*/
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
top--;
T result = stack[top];
stack[top] = null;
return result;
}
/*Returns a reference to the element at the top of this stack.
The element is not removed from the stack.*/
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top-1];
}
//Returns true if this stack is empty and false otherwise.
public boolean isEmpty()
{
for(int i = 0; i < stack.length; i++)
{
if (stack[i] == null)
emptyCount++;
}
if(emptyCount != stack.length-1)
return false;
else
return true;
}
//Returns the number of elements in this stack.
public int size()
{
return stack.length;
}
//Returns a string representation of this stack.
public String toString()
{
String output = "The element at the top of the stack is: " + peek() + "\n" +
"It is " + isEmpty() + " that the stack is empty." + "\n" +
"The number of elements in the stack is: " + size();
return output;
}
}
And my driver/test file:
public class StackTest
{
public static void main(String[] args) throws EmptyCollectionException
{
ArrayStack stack = new ArrayStack(5);
System.out.println(stack);
}
}
Your problem is the isEmpty() method. The stack is empty when top==0 and has nothing to do with the contents of the stack elements.
i guess the problem is in the peek() function and not in isEmpty()
in peek() you use stack[top - 1] which means stack[-1]
another problem though is the size() function... it doesn't return the number of elements in the stack but the length of the stack.
the problem is in your isEmpty() method. Try do something like this
public boolean isEmpty()
{
for (T element : stack)
{
if(element != null)
{
return false;
}
}
return true;
}
another problem is your size function, it always returns the length of the array.
try do something like this:
public int size()
{
int count = 0;
for (T element : stack)
{
if(element != null)
count++;
}
return count;
}

Categories