hello.. i really need help.. I don't know why i keep on getting an empty stack if i pop a token from stack even if user has already push a token into it..

public class MStack implements Stack{

	public Node top;
	public Node[] stack;
	public static int T[];
	public static int B[];
	public static int oldT[];
	public static int i;
	int size2;
	int noOfStack;


	class Node{
		Object info;
		Node link;
	}

	public MStack(){

	}

	public MStack(int size, int noOfStack){
		size2= size;
		stack = new Node[size];
		T = new int[noOfStack + 1];
		B = new int[noOfStack + 1];
		for (int i = 0; i < noOfStack+1; i++){
			B[i]= (int)Math.floor(size/noOfStack) * i -1;
			T[i] = B[i];
		}
	}

	public Object top(int i){
		if (isEmpty(i)){
			System.out.println("Stack empty.");
		}return top.info;
	}

	public void push(String item,int i ) {
		if (T[i]== B[i+1]){
				System.out.println("Stack"+ i + "is full.");
		}else{
			Node newNode = new Node();
			newNode.info = item;
			newNode.link = top;
			top = newNode;
			System.out.println("You have pushed an element into stack");
		}
	}

	public Object pop(int i ){
		Node temp[] = new Node[noOfStack];
		if (isEmpty(i)){
			System.out.println("Stack has nothing inside it");
		}
		temp[i] = top;
		top = top.link;
		return temp[i].info;
	}

	public boolean isEmpty(int i){
		return (T[i] == B[i]);
	}

	public int size(int i){
		int size = T[i] - B[i] ;
		return size;
	}
}

this is another class. This has the main type:

import java.io.*;

public class BookShelf extends MStack {

		public static InputStreamReader ir = new InputStreamReader(System.in);
		public static BufferedReader bf = new BufferedReader(ir);
		public static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		public static MStack bookShelf;
		public static int size;
		public static int shelf;

		public static void main (String []args) throws IOException{
			System.out.println("What size do you want your bookshelf to be?(integer):");
			size =	Integer.parseInt(in.readLine());
			System.out.println("How many shelves do you want your bookshelf to have?:");
			shelf = Integer.parseInt(in.readLine());
			bookShelf = new MStack(size, shelf);

			new BookShelf();
		}

		public BookShelf(){
			super();
			options();
		}
		public void options(){
			try{
				do{
					System.out.println("\nPlease choose from below. Use numbers to choose.");
					System.out.println("1. Place book on shelf");
					System.out.println("2. Retrieve book from shelf");
					System.out.println("3. View books on each shelf");
					System.out.println("4. Exit");
					int choice = Integer.parseInt(in.readLine());
					if  (choice == 1){
						System.out.println("Which shelf do you want to place a book?");
						System.out.println("Enter either 1, 2 or 3");
						int placement = Integer.parseInt(in.readLine());
						if(placement == 1){
							System.out.println("Enter element:");
							String item = bf.readLine();
							garwick(placement);
							bookShelf.push(item, placement);
						}if(placement == 2){
							System.out.println("Enter an element:");
							String item = bf.readLine();
							garwick(placement);
							bookShelf.push(item, placement);
						}if(placement == 3){
							System.out.println("Enter an element:");
							String item = bf.readLine();
							garwick(placement);
							bookShelf.push(item, placement);
						}
					}else if (choice == 2){
						System.out.println("Which shelf do you want to retrieve a book, 1, 2, or 3?");
						int choice2 = Integer.parseInt(in.readLine());
						switch (choice2){
							case 1 : if (bookShelf.isEmpty(choice2)) {
										System.out.println( " Shelf " + choice2 + " is empty!");
									}else {
										System.out.println("Item" + bookShelf.pop(choice2)+ " is retrieved.");
									}break;
							case 2 : if (bookShelf.isEmpty(choice2)) {
										System.out.println(" Shelf " + choice2 + " is empty!");
									}else {
										System.out.println("Item" + bookShelf.pop(choice2)+ " is retrieved.");
									}break;
							case 3 : if (bookShelf.isEmpty(choice2)) {
										System.out.println(" Shelf " + choice2 + " is empty!");
									}else {
										System.out.println("Item" + bookShelf.pop(choice2)+ " is retrieved.");
									}break;
							}
					}else if(choice == 3){
						System.out.println("Recent items");
						for (int i = 1; i <= shelf; ++i) {
							System.out.println("shelf #" + i + ": " + bookShelf.top(i));
							}
							System.out.println("shelf #" + i + ":  Empty");
					}else if (choice == 4){
						System.out.println("You have exited. Thank you!");
						break;
					}
			}while (true);
		}catch(IOException e){}
	}

		/*
		 * Method that implements garwick's algorithm for reallocating free space
		 * within a multiple stack
		 */
		public void garwick(int i) {
			int diff[] = new int[shelf + 1];
			int size[] = new int[shelf + 1];
			int totalSize = 0;
			double freecells, incr = 0;
			double alpha, beta, sigma = 0, tau = 0;
			/* Compute for the allocation factors */
			for (int j = 1; j <= bookShelf.noOfStack; j++) {
				size[j] = bookShelf.size(j);
				if ((bookShelf.T[j] - bookShelf.oldT[j]) > 0){
					diff[j] = bookShelf.T[j] - bookShelf.oldT[j];
				}else{
					diff[j] = 0;
					totalSize += size[j];
					incr += diff[j];
				}
			}
			diff[i]++;
			size[i]++;
			totalSize++;
			incr++;
			freecells = bookShelf.size2 - totalSize;
			alpha = 0.10 * freecells / bookShelf.noOfStack;
			beta = 0.90 * freecells / incr;
			/* If all stacks are full */
			if (freecells < 1)
				throw new StackException("Stack overflow: All Stacks are full");
			/* Compute for new bases */
			for (int j = 2; j <= bookShelf.noOfStack; j++) {
				tau = sigma + alpha + diff[j - 1] * beta;
				bookShelf.B[j] = bookShelf.B[j - 1] + size[j - 1] + (int) Math.floor(tau)- (int) Math.floor(sigma);
				sigma = tau;
			}
			/* Restore size of the overflowed stack to its old value */
			size[i]--;
			System.out.println("size[" + i + "] = " + size[i]);
			/* Compute for new top addresses */
			for (int j = 1; j <= bookShelf.noOfStack; j++) {
				bookShelf.T[j] = bookShelf.B[j] + size[j];
			}
			bookShelf.oldT = bookShelf.T;
		}
}

It implements the Stack interface.
I run this on eclipse compiler.
Can someone help me please.. thanks a lot.. i really need to finish this asap..

Recommended Answers

All 16 Replies

hello! may i know wat T[] and oldT[] represent? how do u derive them?

Can you post the error you are getting? It should include the line number, method names, and error name... info that would be incredibly helpful in helping you.

hello! may i know wat T[] and oldT[] represent? how do u derive them?

T[] refers to he top and oldT[] is the old top.. becuase in the garwick's algo, oldT will get new T when new base pointers, represented as B[], are computed.

Can you post the error you are getting? It should include the line number, method names, and error name... info that would be incredibly helpful in helping you.

when you put an item in the shelf, is done by push method, and then try to retreive the item, done by pop, i doesn't have error, only just print's stack empty.. because i did specify in the code that if empty print to console Satck is empty. the program continues to run.

ok w8, i got this recenlty

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at MStack.push(MStack.java:45)
at BookShelf.options(BookShelf.java:48)
at BookShelf.<init>(BookShelf.java:24)
at BookShelf.main(BookShelf.java:19)

Those T[], B[], and oldT[], keeps track of which stack you want, either stack1, stack2, and stack3.
If i chose stack1 to put an item, it pushes and is ok,but if i try to pop the item in which i put in stack1, it says stack empty. If i try to view what is inside the stack 1 2 3, i get stack 1 = the item i just pushed, stack 2 = the item i just pushed, and stack 3 = the item i just pushed, which is wrong because i only pushed an item in stack 1.

kung pwde k mgbisaya ok lng, pasabta lng ko sa T[] ug OldT[] ug nganong k2ng sa Fig 1.13 (page 35) sa JEDI course notes dili masabtan :(

commented: English please -1

kung pwde k mgbisaya ok lng, pasabta lng ko sa T[] ug OldT[] ug nganong k2ng sa Fig 1.13 (page 35) sa JEDI course notes dili masabtan :(

Did you just swallow an ostrich size fly ?

Did you just swallow an ostrich size fly ?

LOL!!! :)) im sorry i had to speak in our dialect... its just that i cud express myself better that way, sorry :)

LOL!!! :)) im sorry i had to speak in our dialect... its just that i cud express myself better that way, sorry :)

and you have any reason to believe there's any one other than you on this forum that has even the slightest idea of what you said in that post?

Your code in "push" takes two arguments: An integer representing the index you're "pushing" the item onto, and the item that you want to push onto the stack. You got the Exception because you tried to push an item onto the stack at index = 3, but the array is too small; therefore, you can't push anything onto index 3 since it doesn't have 3 indexes.

Why do you need to give the 'push' method an index, anyway? Instead, you could have a variable 'currentSize' in the MStack class that keeps track of how large your stack is. Then, in your push() method, you'd just automatically add the new item onto the end and increment the 'currentSize' variable.

A possible problem: Since you are using an array, and not an Arraylist, you need to make sure that you allocate enough space (make the array big enough) to begin with. Otherwise, at some point, you might get an ArrayIndexOutOfBoundsException. If your array reaches it's maximum size (or at some point before it reaches its max size), you will have to make a new array which has a bigger size and copy the old one over to it. So somehow you're either not making your array big enough or you're calculating the wrong index (that you pass to the push method).

Y

Why do you need to give the 'push' method an index, anyway? .

Because i was thinking that if the index is 1, then it would refer to the stack 1 and it would push the item in that stack.

So you have multiple stacks, then. What I said still applies... you're either not allocating enough space or you're trying to put something in the array at the wrong index. You might want to also check that you actually allocated the space to begin with and that the array isn't null.

kung pwde k mgbisaya ok lng, pasabta lng ko sa T[] ug OldT[] ug nganong k2ng sa Fig 1.13 (page 35) sa JEDI course notes dili masabtan :(

Actually , i also didn't undertsand much about the T[] and oldT[] discussed int our lectures. As i know, T[] refers to the new tops that are computed using the garwick also in allocating memery. oldT[] will piont to the tops before the memory allocation happened.

So you have multiple stacks, then.

That's what im trying to do in the first place. :)

What I said still applies... you're either not allocating enough space or you're trying to put something in the array at the wrong index. You might want to also check that you actually allocated the space to begin with and that the array isn't null.

i did this:

public Node[] stack; // this is supposedly my array
               stack = new Node[size2]; // this is what i had to initialize the size of the stack, in which the user prompts.

how do i access each stack anyway? i had those T[] (top) and B[] (base pointer) to be able to keep track of the stack but i don't know how to use them to access the stack. Or do i use them to acces the stack?

I don't know if you had run my program. but if you could, or somebody else could, i'd appreciate it very much..

newNode.link = top;
top = newNode;


These lines of code don't make sense. Whatever the current 'top' Node is, you should be assigning it's 'next node' pointer to newNode. Since you're keeping it in an array, you could just drop the whole 'linked list' thing and put your stack in the array. It seems you are mixing concepts.

Since you're keeping it in an array, you could just drop the whole 'linked list' thing and put your stack in the array. It seems you are mixing concepts.

I can't do that, cause my job has to be linked list. :)
I'm pretty sure i am clear of what i want, but can't understand how to do it.. :|
thanks for your replies.

here's the edited code;

public class MStack implements Stack{

	public Node top;
	public Node[] stack;
	public int T[];
	public int B[];
	public  int oldT[];
	public static int i;
	int size2;
	int noOfStack2;


	class Node{
		Object info;
		Node link;
	}

	public MStack(){

	}

	public MStack(int size, int noOfStack){
		size2= size;
		noOfStack2 = noOfStack;
		stack = new Node[size2];
		T = new int[noOfStack2 + 1];
		B = new int[noOfStack2 + 1];
		oldT = new int[noOfStack2 + 1];
		for (int i = 0; i < noOfStack2; i++){
			B[i]= (int)Math.floor(size2/noOfStack2) * i -1;
			T[i] = B[i];
			B[noOfStack2] = size2- 1;
		}B[noOfStack2] = size2 - 1;
	}

	public Object top(int i){
		return top.info;
	}

	public void push(String item,int i ) {
		if (T[i]== B[i+1]){
				System.out.println("Stack"+ i + "is full.");
		}else{
			stack[i] = new Node();
			stack[i].info = item;
			stack[i].link = top;
			top =stack[i];
			System.out.println("You have pushed " + item + " into stack!");
			T[i]++;
		}
	}

	public Object pop(int i ){
		Node temp;
		if (isEmpty(i))
			throw new StackException("Stack underflow.");
			temp = top;
			top = top.link;
		return temp.info;
	}

	public boolean isEmpty(int i){
		boolean ques = false;
		if(T[i] == B[i]){
			ques = true;
		}
		return ques;

	}

	public int size(int i){
		int size[]= new int[i];
		size[i] = T[i] - B[i] ;
		return size[i];
	}

}
import java.io.*;

public class BookShelf extends MStack {

		public  InputStreamReader ir = new InputStreamReader(System.in);
		public  BufferedReader bf = new BufferedReader(ir);
		public  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		public  MStack bookShelf;
		public  int size;
		public  int shelf;

		public static void main (String []args) throws IOException{
			new BookShelf();
		}

		public BookShelf()throws IOException{
			super();
			options();
		}

		public void options()throws IOException{
			System.out.println("What size do you want your bookshelf to be?Integers only.:");
			size =	Integer.parseInt(in.readLine());
			System.out.println("How many shelves do you want your bookshelf to have?:");
			shelf = Integer.parseInt(in.readLine());
			bookShelf = new MStack(size, shelf);
			System.out.println("You have now a book shelf with " +size+ " capacity and " +shelf+ " shelves" );
			try{
				do{
					System.out.println("\nPlease choose from below. Use numbers to choose.");
					System.out.println("1. Place book on shelf");
					System.out.println("2. Retrieve book from shelf");
					System.out.println("3. Show items on shelf");
					System.out.println("4. Exit");
					int choice = Integer.parseInt(in.readLine());
					if  (choice == 1){
						try{
							System.out.println("Which shelf do you want to place a book?(Integers only");
							int placement = Integer.parseInt(in.readLine());
							int i;
							if(placement == 1){
								i = 0;
								System.out.println("Enter element:");
								String item = bf.readLine();
								bookShelf.push(item,i);
							}if(placement == 2){
								i = 1;
								System.out.println("Enter an element:");
								String item = bf.readLine();
								bookShelf.push(item,i);
							}if(placement == 3){
								i = 2;
								System.out.println("Enter an element:");
								String item = bf.readLine();

								bookShelf.push(item,i);
						}
						}catch(ArrayIndexOutOfBoundsException e){

							}
					}else if (choice == 2){
						System.out.println("Which shelf do you want to retrieve a book? Integers only.");
						int choice2 = Integer.parseInt(in.readLine());
						try{
							switch (choice2){
								case 1 : if (bookShelf.isEmpty(choice2)) {
											System.out.println("Shelf is empty");
											break;
										}else{
											System.out.println("Item " + bookShelf.pop(choice2)+ " is retrieved.");
											break;
										}
								case 2 : if (bookShelf.isEmpty(choice2)) {
											System.out.println("Shelf is empty");
											break;
										}else{
											System.out.println("Item " + bookShelf.pop(choice2)+ " is retrieved.");
											break;
										}
								case 3 : if (bookShelf.isEmpty(choice2)) {
											System.out.println("Shelf is empty");
											break;
										}else{
											System.out.println("Item " + bookShelf.pop(choice2)+ " is retrieved.");
											break;
										}
								}
						}catch(NullPointerException e){

						}
					}else if (choice == 3){
						for (int i = 0; i <= shelf; ++i) {
							if (!isEmpty(i)){
								System.out.println("shelf #" + i + ": " + bookShelf.pop(i));
							}else{
								System.out.println("shelf #" + i + ": is empty.");
								break;
							}
						}

					}else if ( choice == 4){
						System.out.println("You have exited. Thank you!");
						break;
					}
			}while (true);
		}catch(IOException e){}
	}


}

I can now push strings onto shelf , 2, and 3 BUT i think it is in a single stack.. :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.