Stack or array ?

hi,
i have 4 integers like
int a = 30;
int b = 57 ;
int s = 36 ;
int d = 30;
int total = a + b + c + d ;
and i want to random them to get 6 in an array
like
array[0] = a
array[1] = c
array[2] = b
array[3] = d
array[4] = a
array[5] = b
now we got 2x a so i want to do a = 2- a ; and keep randoming until total = 0 and all others are 0
and i want to keep calling the random method from another class. but i want to random for example a more then 30 times becouse a = 30
i made this code but here i get negative integers
public class Bag
public static void main(String args[]) {
int settlementTile = 30;
int templeTile = 57 ;
int farmTile = 36 ;
int marketTile = 30;
int totalTile = settlementTile + templeTile + farmTile + marketTile ;
int RandomArray[] = new int [154];
for (int i = 0; i <= 5; i++ ) {
RandomArray[i] = 1+ (int) (Math.random() * 4 );
System.out.println("random "+i+ "=" + RandomArray);
if (RandomArray[i] == 1 ){
settlementTile = settlementTile - 1; }
if (RandomArray[i] == 2 ){
templeTile = templeTile - 1; }
if (RandomArray[i] == 3 ){
farmTile = farmTile - 1; }
if (RandomArray[i] == 4 ){
marketTile = marketTile - 1; }
totalTile = settlementTile + templeTile + farmTile + marketTile ;
System.out.println("settlementTile="+ settlementTile );
System.out.println("templeTile="+ templeTile );
System.out.println("farmTile="+ farmTile );
System.out.println("marketTile=" + marketTile );
System.out.println("totalTile="+ totalTile );
i didnt made the constuctor method there yet.
if using a stack beter idea? putting all intergers randomed in the stack and then getting then one by one ? or is it pobbible to tell to the code i made stop randoming for example a if a = 0 but keep randoming the rest until total = 0
its a long story but i hope someone can help me with it

its working now thanks alot. i puted the array in the vector.
how can i random 153 integers
which this 153 are the sum of the following
int settlementTile = 30;
int templeTile = 57 ;
int farmTile = 36 ;
int marketTile = 30;
i want to random it so that it dont random for example farmTile more then 36 time becouse farmTile = 36 ;
i tried this
int RandomArray[] = new int [153];
Vector v = new Vector();
for (int i = 0; i <= 5; i++ ) {
RandomArray[i] = 1+ (int) (Math.random() * 4 );
System.out.println("random "+i+ "=" + RandomArray);
if (RandomArray[i] == 1 ){
settlementTile = settlementTile - 1; }
if (RandomArray[i] == 2 ){
templeTile = templeTile - 1; }
if (RandomArray[i] == 3 ){
farmTile = farmTile - 1; }
if (RandomArray[i] == 4 ){
marketTile = marketTile - 1; }
totalTile = settlementTile + templeTile + farmTile + marketTile ;
v.addElement(new Integer(RandomArray[i]));
int x = ((Integer)v.elementAt(i)).intValue();
but here i can get negative int's if i put
the for loop to
for (int i = 0; i <= 152; i++ )

Similar Messages

  • Stack ADT using array

    Hi everyone, I posted a similar question earlier and thought I got the response I wanted but I keep running into problems.
    I'm looking to make my own version of the stack ADT using arrays (or arraylist).
    I have created my own isEmpty() method. Here is part of my code:
    public interface StackADT<T> {
         void push(T element); // adds an element to the stack
         T pop(); // removes an element from the stack and returns it
         boolean isEmpty(); // returns true if the stack is empty and false otherwise
         T peek(); // returns top element from the stack without removing it
         void truncate(); // truncates the stack to the exact number of elements
         void setExpansionRule(char rule); // sets expansion to either doubling or increasing by 10 elements
    public class Stack<T> implements StackADT<T> {
              private T[] array;
              int index = 0;
              public Stack(){
                   this.array = (T[]) new Object[50];
              public boolean isEmpty(){
              if (index == 0){
                   return true;
              return false;
               public T pop(){
                    if(Stack<T>.isEmpty()){  //ERROR
                     throw new EmptyStackException("Stack is empty");     
    }I'm trying to use my isEmpty() method (also part of the stack class) inside other methods like pop(). Problem is it says: "T cannot be resolved to a variable, Stack cannot be resolved to a variable". I also tried Stack.isEmpty(), but it doesn't work. I'm really confused. Any suggestions?
    Edited by: Tiberiu on Mar 1, 2013 6:38 PM

    >
    Hi everyone, I posted a similar question earlier and thought I got the response I wanted but I keep running into problems.
    I'm looking to make my own version of the stack ADT using arrays (or arraylist).
    I have created my own isEmpty() method. Here is part of my code:
    >
    No - you haven't. There is no 'isEmpty' method in the code you posted.
    We can't debug code that we can't see. You haven't posted any interface and you haven't posted anything that calls any of the limited code that you did post.
    You did post code that tries to call the method on the class instead of an instance of the class.
    if(Stack<T>.isEmpty()){ 

  • Query on Stack

    Could someone show me where I am going wrong in my incomplete answers to the following questions:
    Question:
    Software for a Web search engine requires the use of a class Stacker which just implements the functionality of a Stack associated with the methods empty(), peek(), pop(), and push(); it should not implement any of the functionality of the Vector class which Stack inherits from.
    (i) What variables would you use in this class? Before answering this part of the question we would advise you to read the remainder of the question.
    My answer:
    //instance variables
    private int count;//number of objects in the Stacker
    private int maxSize;//maximum size of Stacker
    private int top;//index of top of the Stack
    private Object obj;
    static variable;
    private static final int noOfStackers; //maximum number of Stacker objects allowed to be created
    Question:
    Write down code for the four methods detailed above, their functionality is described below:
    (ii) empty() � returns true if the Stacker is empty and false otherwise.
    My Answer:
    public boolean empty(){
    return count= =0;
    Question:
    (iii) peek() � returns with the top object of the Stacker; this top object is not removed
    My answer:
    public Object peek(){
    return Object obj;
    Question:
    (iv) pop() � removes the top object from the Stacker and returns it
    My answer:
    public Object pop(Object removedObj){
    int i=top;
    int j=top-1;
    i=j;
    count--;
    return removedObj;
    Question:
    (v) push() � places and object in the Stacker
    My answer:
    public void push(Object addedObject){
    top=addedObject;
    count++;
    Question
    (vi) In addition to this the class should contain a constructor Stacker which has two int arguments. The first argument gives the maximum size of the Stacker and the second argument gives the maximum number of Stackers that may be created by a program.
    My answer:
    public Stacker(int max, int nos) {
    maxSize=max;
    noOfStackers =nos;
    if (nos> noOfStackers)
    Question:
    (vii) Finally the class should contain a method setMaxStacks which has a single int argument which is the maximum number of Stackers that can be created
    If the stack size is exceeded a StackOverflowException should be thrown; if a program creates more Stack objects than is allowed a TooMany StackersException is thrown
    Do not write any code which caters for errors
    My answer:
    public void setMaxStacks(int maxNoStackers) throws StackOverFlowException, throws tooManyStackersException {
    noOfStackers=maxNoStackers;
    }

    (i) What variables would you use in this class?You need to store more than the top object, which is all you currently store. I would suggest that instead of obj you have private Object[] stack. Now, building with the base of the stack at array offset 0, you don't need top because it's always the case that top == count - 1. Nor do you need maxSize, because maxSize == stack.length. And since there is a method setMaxStacks, noOfStackers should not be final. Also you need a static variable to count the number of Stackers which have been instantiated so far - e.g. private static int stackersInstantiated.
    // Tidied up a bit
    public boolean empty(){
    return (count == 0);
    }Correct.
    peek() will need to look at the last defined element of the array stack, so peek() just returns stack[count - 1].
    pop() is the same as peek, except that it decrements count. For tidiness' sake, you should remove the object from the stack. So public Object pop()
        Object popped = peek();
        stack[count - 1] = null;
        count--;
        return popped;
    } A sensible spec would tell you to throw an exception if there is nothing to pop (and ditto for peek), but the one given doesn't. Unless that's what it means by
    Do not write any code which caters for errorsLeft as an exercise for the reader.
    The push method has to throw an exception if the stack size is exceeded. So public void push(Object obj) throws StackOverFlowException
        if (count == stack.length)
            throw new StackOverFlowException();
        stack[count++] = obj;
    } Next, the constructor. This has two arguments and can throw a TooManyStackersException. The spec really breaks down into gibberish here. public Stacker (int maxSize, int newNoOfStackers) throws TooManyStackersException
        noOfStackers = newNoOfStackers; // I think this is the appropriate thing to do.  As I say, the spec is gibberish.
        if (stackersInstantiated >= noOfStackers)
            throw new TooManyStackersException();
        stack = new Object[maxSize];
        count = 0;
    } Finally, the trivial setMaxStacks. public void setMaxStacks(int newNoOfStackers)
        noOfStackers = newNoOfStackers;

  • Question about creating Stack!!

    Can someone please help me....I need help on creating a stack..I don't understand the whole point of stack..I help on how to this question...please show me how to start this question..
    You are to implement a class called Stack using arrays as internal storage mechanisms . Note well, you cannot use the java Stack class. You are to implement the following instance methods (interfaces are provided below)....etc

    It sounds to me as if you need to understand the nature of a stack before you go about implementing it. Use http://www.google.com and search for "stack data structure java". There are a number of good references available there.
    Chuck

  • Push() and pop()

    I'm writing my own Stack class, in which I'm using a 100 element String array. I'm trying to write the push and pop methods for this class. I'm having trouble figuring out how to add an element to my array in the push method.
    Here is my code so far:
    public class Stack
         String array[] = new String[100];
         int c = 0;
        public Stack()
        public voide clear()
          c = -1;
        public void push(String x)
       public String pop()
           throws EmptyStackException
           return null;
    }So if someone could please help me with my push and pop methods. Thanks

    Ok here is what I came up with after all of your help. I'm not sure if it's correct, because I have to use an text file that already has input in it to test it. If you want to see exactly what I have to do, go to this site:
    http://webmail1.uwindsor.ca/Redirect/davinci.newcs.uwindsor.ca/~angom/cs254/
    here is my code now:
    public class Stack
         String array[] = new String[100];     
         int top=0;
         public Stack()
         public void clear()
              top=-1;
         public void push(String x)
              for(int i=0; i < array.length; i++)
              array[i] = x;
              top = i;
         public String pop()
              throws EmptyStackException
              if(top > 0)
                   for(int j=0; j < array.length; j++)
                        System.out.print(array[j]);
              top = top - 1;
              return null;
    }And this is the code so for the reading in of the file
    import java.io.*;
    import java.util.*;
    public class Assign1 
       static BufferedReader in;
       static StringTokenizer toke;
       public static void main (String args[]) throws Exception
           Stack stack = new Stack();
               in = new BufferedReader(new InputStreamReader (System.in));
           //you can now use in to read in a full line
           //System.out.println("type something");
           System.out.println(in.readLine());
           //to break up a line use stringTokenizer
           //System.out.println("type something again with a space");
           String line = in.readLine();
           toke = new StringTokenizer(line);
           System.out.print(toke.nextToken());
           if (toke.hasMoreTokens()) System.out.println(" " + toke.nextToken());
    Thanks again for all of everyone's help

  • Store Moves to memory

    I have a simple twist on the hunt the Wumpus game where the object is to find a pile of smelly socks and then return to the starting position. My code is very basic and not the most intelligent agent but it gets the job done. the problem I am having is returning to the starting position. I have considered using an array or a stack but I am unsure how to implement it. Thanks for reading
    import java.applet.Applet;
       import java.util.Random;
       import javax.swing.JOptionPane;
        public class WumpusWorld extends Applet
           public void init ()
             Room   edsRoom = new Room("wumpusworld.room", this);
             Butler james   = new Butler (18, 3, edsRoom);
             System.out.print(james.getX());
           System.out.print ( james.getY()); 
             edsRoom.waitForStart();
             int[] move = new int[600];
             int index = 0;
             Random rand = new Random();
             while(true)
                while(james.isFrontClear() == true)
                   james.forward();     
                   move[index]++;
                              System.out.print(move[index]+"Shit\n");
                while(james.isFrontClear() == false && james.isLeftClear()||james.isRightClear())
                   if(Math.random() < .25)
                      james.turnLeft();
                   else if(Math.random() < .25)
                      james.turnRight();
                   while(james.isFrontClear())
                      james.forward();
                      move[index]++;
                   if(james.isFrontClear() == false && james.isLeftClear() == false && james.isRightClear() == false)
                      james.backward();
                      james.turnLeft();
                   if(james.senseSmell() == 96 && james.seeSocks())
                      james.pickUp();
                      james.forward();
                      move[index]--;
                      System.out.print(move[index]+"Number of moves");
                                  String outputStr;
                                  outputStr = "Health"+james.getHealth();
                                  JOptionPane.showMessageDialog(null,outputStr,"HEALTH",JOptionPane.INFORMATION_MESSAGE);
                                  System.out.print(james.getHealth());            
                while(true)
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());
                   System.out.println(james.seeSocks());
                   james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());
                   System.out.println(james.seeSocks());
                //james.forward();
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.forward();
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.turnLeft();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());     
                   System.out.println(james.seeSocks());
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());
                   System.out.println(james.seeSocks());
                //james.forward();
                   System.out.println(james.senseSmell());
                   System.out.println(james.senseBreeze());
                   System.out.println(james.senseHeat());
                   System.out.println(james.seeSocks());
                //if (james.seeSocks()) james.pickUp();
                   System.out.println(james.getHealth());
             //james.turnLeft(2);
             //james.forward(4);
             //james.turnRight();
             //james.forward(7);
       }

    I looked into the approaches and I appreciate the idea because I had never heard of those algorithms before and for a more advanced project i will look into those. I think for this project a stack or array will be more ideal. I have a working stack now that stores a value for each move. forward = 1, backward = -1, left = 2, and right = 3. Now i dont know how to go about the pop. should i use a case switch or if statements. The plan is to swap the values, that is when bactracking backward = 1, forward = -1, right = 2, and left = 3. here is the new code.
       import java.applet.Applet;
       import java.util.Random;
       import javax.swing.JOptionPane;
       import java.util.*;
        public class WumpusWorld extends Applet
           public void init ()
             Room   edsRoom = new Room("wumpusworld.room", this);
             Butler james   = new Butler (18, 3, edsRoom);
             edsRoom.waitForStart();
             int direction = 0;
             boolean n = true;
                        Random rand = new Random();
             Stack movesMade = new Stack();
             while(james.seeSocks() == false)
                if(james.isFrontClear() == true){
                   james.forward();
                   movesMade.push(new Integer(1));
                    if(james.isFrontClear()
                      james.forward();
                      movesMade.push(new Integer(1));
                   if(james.isFrontClear() == false && james.isLeftClear()||james.isRightClear())
                   direction = rand.nextInt(2);
                      if(direction == 0)
                         james.turnLeft();
                         movesMade.push(new Integer(2));
                      else if(direction == 1)
                         james.turnRight();
                         movesMade.push(new Integer(3));
                   if(james.isFrontClear() == false && james.isLeftClear() == false && james.isRightClear() == false)
                      james.backward();
                      movesMade.push(new Integer(-1));
                      james.turnLeft();
                      movesMade.push(new Integer(2));
                   else if(james.senseSmell() == 96 && james.seeSocks() )
                      james.pickUp();
                      break;
                while(!movesMade.empty())
              // Insert backtracking pop here

  • How to iterate contents of a directory?

    How do I iterate all the files and subdirectories of a directory, whose depth I don't know?

    A rough idea, you could do it recursively, but this is easier:
    import java.util.Stack;
    import java.util.Arrays;
    public
    class Pops
      public
      static
      void main(String[] args)
        File file = new File(args[0]);
        Stack stack = new Stack();
        Stack files = new Stack();
        stack.add(file);
        stack.addAll(Arrays.asList(file.listFiles()));
        while (!stack.empty())
          file = (File)stack.pop();
          if (file.isDirectory()) { stack.addAll(Arrays.asList(file.listFiles())); }      files.push(file);
        while (!files.empty())
          System.out.println(files.pop());

  • Make the program understand Inputted Arithmetic Code

    hello guys,
    i want to make a graphing calculator
    i already have to code to determine the coordinates of a certain formula..
    the problem now is, how can i make a certain arithmetic formula like for ex. *sqrt(x^2 PLUS 4x PLUS 4)* and make the program understand it.. (sorry, the forum just removes the PLUS SIGN wen i include it on the formula :3 )
    it will be inputted through Java GUI like a scientific calculator..
    i have tried studying using stacks and arrays for these but it just i can't implement the theory behind it to my program..
    i already know the infix conversion to postfix or prefix but i just don't know how my program can interpret that
    i need some enlightenment or tips on how can i do that with my current program..
    right now, my program can only graph a certain formula when i edit it on the code and let the program run so it can be graphed [LIKE THIS|http://forums.sun.com/thread.jspa?messageID=11038067#11038067]
    Edited by: kyzhuchan on Sep 3, 2010 7:14 AM
    Edited by: kyzhuchan on Sep 3, 2010 7:15 AM

    I would use a stack for that.
    First you translate the equation into a postfix form and then you evaluate that.
    Here is an example
    import java.util.*;
    public static double calc(List postFix, double x) {
        Stack<Double> stack=new Stack<Double>();
        for(Object o: postFix) {
            if(o instanceof Double) stack.push((Double)o);
            else if(o instanceof String) {
                String str=(String)o;
                if(str.equals("x")) {
                    stack.push(x);
                } else if(str.equals("+")) {
                    stack.push( stack.pop() + stack.pop() );
                } else if(str.equals("-")) {
                    stack.push( -stack.pop() + stack.pop() );
                } else if(str.equals("*")) {
                    stack.push( stack.pop() * stack.pop() );
                } else if(str.equals("/")) {
                    stack.push( 1.0 / stack.pop() * stack.pop() );
        return stack.pop();
    }Lets say the formula is (2.3 + 5.1) * (7 - 4) * xThe postfix form is 2.3 5.1 + 7 4 - * x *Then to calculate the value at x=4.3 you can do
    List<Object> postFix=Arrays.<Object>asList(2.3, 5.1, "+", 7.0, 4.0, "-", "*", "x", "*");
    System.out.println(calc(postFix, 4.3));

  • Waveform Chart NOT allowed inside array of clusters; Dynamic plot stacking?

    The NI Developer Zone has a VI that does something I want - dynamically
    stack plots in a useful way. Unfortunately, I would like those plots
    to actually be Waveform Charts and NOT Waveform Graphs (as the
    documentation specifies but LIES!)
    A little further experimentation shows you that it is seemingly not
    possible to make an array of clusters that contain Waveform Charts!
    Why?
    Alternatively, are there any other ways to smartly show many signals at
    once? I have found multiplots to be frustrating as it is difficult to
    assign the number of plots once you start the VI (hence the existence
    of Dynamic Stack Plots).
    DynamicStackPlots here:
    http://sine.ni.com/apps/utf8/niepd_web_display.display_epd4?p_guid=B123AE0CB938111EE034080020E74861

    If you have LabVIEW 8.0, have a look at the new "Mixed Signal Graph"
    (see e.g.: http://zone.ni.com/devzone/conceptd.nsf/webmain/C6B79FA61959D9D68625706E006F7462 )
    LabVIEW Champion . Do more with less code and in less time .

  • Creating Stack Of String & Array???

    How can I create a stack of strings and use arrays as internal storage mechanism??n Is it possible to make a stack that can take in a text file?? thanks in advance.:):)

    Of course, if you want a Stack that's better than java.util.Stack, all you have to do is
    public interface Stack {
       public abstract boolean isEmpty();
       public abstract void push(Object newItem);
       public abstract Object pop();
    import java.util.*;
    public final class LinkedStack implements Stack {
       private LinkedList data = new LinkedList();
       public boolean isEmpty() {
          return data.size() == 0;
       public void push(Object newItem) {
          data.addLast(newItem);
       public Object pop() {
          if (isEmpty()) return null;
          return data.removeLast();
    }Implementation of ArrayStack is left as an exercise for the reader.

  • Arrays to stacks

    does anyone know how I can get some numbers from an array into a stack
    thanks
    henry

    A stack is a queue data structure. You access it using the last in first out principle (LIFO) with two methods often called push and pop. You can easily implement a stack using an array like this
    int[] stack = new int[10];
    int index = 0;
    public void push(int e) {
       stack[index++] = e;
    public int pop() {
       return stack[--index];
    }This is a very rudimentary version to show the principle. You'll have to complement it with checks against overflow/underflow. There are also often additional convinience method available, for example isEmpty/isFull.

  • Runtime For Array Stack

    Does anybody know the Big-Oh runtime notation for a Stack using an array. I need to find the runtime notation for each operation (push, pop, top, poAndTop) if the Stack has n items in it. Also the same for each Queue operations( enqueue, dequeue)..
    Thanks
    srj6

    Unless you have to resize your array, stack operations should all take O(1) time. Queues are more interesting - if you're happy with amortized time, you can get O(1) per operation.

  • Array Stack help

    learning stacks in my java class.
    have an assignment with some questions.
    please someone correct me if im wrong, but when you push a number into a stack it goes into an array bassicaly..now does that start at index 0? i mean the first open slot?
    cause if im thinking right the question im givin is that:
    Convention 1: We store items at the low end, starting at index 0(to my knowledge that would be the begging of the array) We use the variable count which equals the number of items on the stack.
    sample questions being asked::
    -Write the code for isEmpty() - I put public boolean isEmpty()
    am i on the right course or is it asking the actual code used to find if it is empty in the code?

    i have created this list of 10 integers array 0,1,2,3,4,5,6,7,8,9;
    i have to pop them out 9,8,7,6,5,4,3,2,1,0
    so far i only managed to be able to print out the list of 10 integers.
    Could any kind soul help???
    System.out.println("\n");
    System.out.println("OPERATION: Reverse an array using a stack");
    System.out.println("\n");
    System.out.println("Set up an array of 10 integer objects");
    int i,j;
         //set 10 array
    int[] nums1 = new int[10];
    int[] nums2 = new int[10];
    for(i=0; i < nums1.length; i++) nums1[i] = i;
    System.out.print("Array 1= ");
    for(i=0; i < nums2.length; i++)
    System.out.print(i);
    System.out.print("\n");
    System.out.print("Stack Content: bottom " + s1 + " top");
    System.out.println("\n");
    System.out.println("Get objects from Array 1, add to stack");
    s1.push(i);
    System.out.println("Stack Content: bottom " + s1 + " top");

  • Push method, arrays, stacks

    public boolean push(String input)
    I have read in the input from the keyboard, using console Reader, but im not sure how to impement the push method, where it returns true if it pushed the string or false if it didnt. I have to push the input from one stack onto another stack. The stacks are built using arrays.
    Can anyone help
    Thanks

    Hi there,
    Stack is a LIFO structure which i presume u already know. I think u are developing a class called Stack .
    Let me give u the psuedocode for the same
    public class Stack
    private String[] elements;
    private int topOfStackPtr = 0;
    // to be initialized in the constructor
    private int length = 0;
    public boolean push(String input)
    try{
    if(topOfStackPtr >= length)
    return false
    elements[topOfStackPtr] = input;
    topOfStackPtr++;
    }catch(ArrayIndexOutOfBoundsException e)
    return false;
    I havent shown u the constructor psuedocode.
    Hope this helps

  • Creating array w/Stacks

    I have the following source which loads 10 elements and then unloads the array. I want it to modify the class which loads one element with 10 animal names and another array with 10 insect names.
    The class should then display the contents of each element of the array as it is 'popped' off the stack. Can someone please help me on modifying the following code:
    // This class defines an integer stack that can hold 10 values.
    class Stack {
    int stck[] = new int[10];
    int tos;
    // Initialize top-of-stack
    Stack() {
    tos = -1;
    // Push an item onto the stack
    void push(int item) {
    if(tos==9)
    System.out.println("Stack is full.");
    else
    stck[++tos] = item;
    // Pop an item from the stack
    int pop() {
    if(tos < 0) {
    System.out.println("Stack underflow.");
    return 0;
    else
    return stck[tos--];
    class TestStack {
    public static void main(String args[]) {
    Stack carNames = new Stack();
    Stack stateNames = new Stack();
    // push some numbers onto the stack
    for(int i=0; i<10; i++) carNames.push(i);
    for(int i=0; i<10; i++) stateNames.push(i);
    // pop those numbers off the stack
    System.out.println("Stack in carNames:");
    for(int i=0; i<10; i++)
    System.out.println(carNames.pop());
    System.out.println("Stack in stateNames:");
    for(int i=0; i<10; i++)
    System.out.println(stateNames.pop());
    TIA,
    Mark
    null

    I have the following source which loads 10 elements and then unloads the array. I want it to modify the class which loads one element with 10 animal names and another array with 10 insect names.
    The class should then display the contents of each element of the array as it is 'popped' off the stack. Can someone please help me on modifying the following code:
    // This class defines an integer stack that can hold 10 values.
    class Stack {
    int stck[] = new int[10];
    int tos;
    // Initialize top-of-stack
    Stack() {
    tos = -1;
    // Push an item onto the stack
    void push(int item) {
    if(tos==9)
    System.out.println("Stack is full.");
    else
    stck[++tos] = item;
    // Pop an item from the stack
    int pop() {
    if(tos < 0) {
    System.out.println("Stack underflow.");
    return 0;
    else
    return stck[tos--];
    class TestStack {
    public static void main(String args[]) {
    Stack carNames = new Stack();
    Stack stateNames = new Stack();
    // push some numbers onto the stack
    for(int i=0; i<10; i++) carNames.push(i);
    for(int i=0; i<10; i++) stateNames.push(i);
    // pop those numbers off the stack
    System.out.println("Stack in carNames:");
    for(int i=0; i<10; i++)
    System.out.println(carNames.pop());
    System.out.println("Stack in stateNames:");
    for(int i=0; i<10; i++)
    System.out.println(stateNames.pop());
    TIA,
    Mark
    null

Maybe you are looking for

  • Macbook pro to hdtv issues

    Hi guys, I have recently purchased a mini displayport to hdmi off of ebay, i am able to get everything connected and working great but at random intervals the tv screen goes grey and fuzzy, a bit like noise you would used to get on older tvs that wer

  • Price update

    Dear Gurus, In the purchase order history price is updated by net price. I want it to be updated by effective price i.e inclusive of taxes. Pls help Thanks, Kumar

  • Touchpad tapping and clicking

    Hello. I have a strange problem with the touchpad. I cannot select internet search result using the touchpad. I tried double tapping, right clicking, left clicking. It just won't work. I have to copy the link and paste the link in the URL. I already

  • Elements 9.0.3 for Mac crashes every time I quit program

    I receive an error every time I quit PSE.  I always do File->Quit to leave the program, but even that causes a crash.  I have the crash file, but because of its length I don't want to post that here, but it might help someone understand the problem. 

  • Download assistant doesn't work

    When I try to start the download assistant all i get is: What do I do?