Java/Java Stack

Advertisement


Question
Hi! I'm trying to create a Space class will represent the (explored) set of states as a stack. The Methods are used to add (push) a state and to remove (pop) a state. This class only adds and removes State objects, and has no knowledge about a State’s data structures or methods. So far, I have this code written but it doesn't seem to be working. This is anything wrong with this code? Thank You

class Space{
  
  
  Object [] Stack;
  int top = -1;
     
  void adds(int a)
  {
     
     top++;
     Stack[top]= a ;

  }
  
   Object remove()
   {
     top--;
     return Stack[top+1];
        
  }
}

Answer
You need to initialize your Stack to an array. Right now it's null so it won't work.

If you want to have a stack of size 10, you can:
Object[] Stack = new Object[10];

Also, I see that you have adds take an int, while remove gives an Object. You should either change adds to take an Object, or change remove and Stack to be int.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.