Looking for help in creating a class to handle a stack

Hi Fellow EE'rs

Could someone please assist me with creating code to handle a stack? What would be the required driver programs needed for this?

Many Thanks
Steve
LVL 19
Stephen MandersonSoftware EngineerAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
close , try more like this:

public class CChar {

       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      Stack stack = new Stack();

      public CChar() {
      }


      public void setCharValFromKeyboard() {
            try {
                  System.out.print("Character to add to stack: ");
                  char charVal = (char) in.read();
                  stack.push(charVal);
                  System.out.println();

            }
            catch (Exception e) {
            }

      }
   
}
0
 
objectsCommented:
0
 
deeppraCommented:
Its already there in the JavaSE so u dont need to recreate it just use that
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
huzefaqCommented:
0
 
Stephen MandersonSoftware EngineerAuthor Commented:
Thanks Objects

Not at my own pc but does the following look ok to setup a stack and add from keyboard input?

public class CChar {

      private char CharVal;


      public CChar() {
            Stack stack = new Stack();
            CharVal = ' ';
      }


      public void setCharValFromKeyboard() {
            try {
                  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                  System.out.print("Character to add to stack: ");
                  CharVal = (char) in.read();
                        stack.push(CharVal);
                  System.out.println();

            }
            catch (Exception e) {
            }

      }
   
}
0
 
deeppraCommented:
Yea its okay
0
 
Stephen MandersonSoftware EngineerAuthor Commented:
Thanks for that

Would it just be a case of the following to remove stack values and to print a stack contents?

public void popStackValue() {
       try {
             System.out.println("The poped value is " + stack.pop());
             System.out.println("The new stack size is" + stack.size());
             }
}

public void printStack() {
      try {
            System.out.println("The contents of  the Stack are" + stack);
            }
}

Would that be the correct way to print out the stack contents?

Many Thanks
Steve
0
 
objectsCommented:
yes, that would be a good start
0
All Courses

From novice to tech pro — start learning today.