Stack implementation

I need help in my assignment to implment a stack with push and pop functions. if anyone is an expert in this section pliz help me out.....

If you want a good implementation look at the source
code for java.util.Stack.That Stack class is not a good implementation of a stack for a couple
of reasons:
1) it extends the Vector class which uses synchronized methods, which
you often don't want. The Stack class had better been retrofitted on a
WhatEverList implementation of the List interface, but even then:
2) The base class (WhatEverList or Vector) is too strongs for a Stack
class, i.e. you don't want to be able to, say, remove elements from the
middle from a stack or take the intersection with another Collection.
kind regards,
Jos

Similar Messages

  • Error in jsr180 sip stack implementation in WTK2.5.2?

    Hi,
    I encountered error in the SIP stack implementation used in the WTK2.5.2.
    When I create a SIP message and fill all the header and add to the request a Route header
    when the created message is sent to the next hop it is send according to the Request URI
    value but not the Route header.
    I try to register my application and force SIP proxy by inserting Route header.
    This done according to RFC 3261 where Route header forces the sip transation to
    forwarded according to the 'highest' value.
    Waiting for Your feedback
    Kind regards
    Tomasz

    I am having exactly the same problem!!!!
    In fact I developed days ago an application with SUBSCRIBE and NOTIFY messages, with the J2ME client as the receiver of NOTIFY requests... the requests arrived, but the responses, once sent, never get to the NOTIFY sender.
    I asked this same question in the following forum:
    http://forum.java.sun.com/forum.jspa?forumID=82
    but at this moment nobody replies...
    Today I was checking the SIPDemo implementation in SWTK2.5, and what was my surprise when I worked out that the implementation gave the same problem... I have tried several settings modifications in the SWTK preferences and settings, but no success.
    Please, is anybody aware of how to resolve this problem??, I really need the answer.
    Ashgar... do you know where can the problem be??

  • Solman configuration before new SP stack implementation

    Hello!
    Solman SP Stack was updated to 18 (without configuration).
    Need I configure SolMan before new stack implementation? Could I do it after import?
    I used solman maintenance optimizer earlier to approve support packages...
    regards,
    Tonya

    You can configure before or after - just make sure that any transports that you create when doing your configuration are released prior to doing the EhP1 Upgrade and you shouldn't have any problems.

  • Stack implementation peforming badly.

    I have a lot of data points (x and y co-ordinates) which will be added to a stack and popped off as necessary.
    Initially i implemented the stack using an ArrayList however when profiling my program i have found that the 'new' operation involved when adding an element to the stack was my program's bottle-neck. So i implemented my own stack based on two integer arrays.
    I thought that this would be much faster as there was no creation of new objects, however this was not the case... infact it performed almost ten times as worse then before.
    Is there something inherently slow/incorrect with my stack implementation?
    code is as follows:
         class MyStack
              int[] x;
              int[] y;
              int index;
              public MyStack()
                   x= new int[1024];
                   y= new int[1024];
                   index=0;
              public int size()
                   return index;
              public void add(int x1,int y1)
                   if (index==x.length)
                        int[] temp= new int[2*x.length];
                        System.arraycopy(x,0,temp,0,x.length);
                        x=temp;
                        temp= new int[2*y.length];
                        System.arraycopy(y,0,temp,0,y.length);
                        y=temp;
                   x[index]=x1;
                   y[index]=y1;
                   index++;
              public int getX()
                   return x[index-1];
              public int getY()
                   return y[index-1];
              public void remove()
                   index--;
         }

    Is this viable? as the stack is not firstly popluated
    before pop operations are peformed, i.e. push and pop
    operations can and do happen at any time. This would
    mean that the timing of the stack until it reaches
    "steady-state" will be by its nature much more than
    the push and pops after.Yes it would, but then you will get a feeling for what takes time in your stack, internal restructuring or the actual stack operation. You can make an artificial test. First make N (quite large) pushes, so the stack grows, and time that, then make the same number of alternating push/pop operations, so the size won't change, and time that. The difference basically is the internal restructuring of the stack.
    I'd say this will show that the second phase has become much faster now that you don't have to do create two new Integer objects for each push. If you can anticipate the stack-size you should make it that big from the start.

  • SIP stack implementation in WTK2.5

    Hello friends,
    I want to implement the SIP communication in J2ME. I am using the wtk2.5 emulator where the SIP stack has been implemented. I followed the tutorial provided by sun and now position is as follows:
    1. I can send SIP requests to a SIP server.
    2. The SIP server is responding to the request BUT my J2ME application is not receiving it.
    So I tried the example application SIPDemo provided with wtk2.5 toolkit. As far as I studied the program it is performing the following operations:
    1. Receiver:
    i. Opens a SIP server port at a particular port (say 5060)
    ii. Waits for client.
    iii. When client connects it receives message from the client.
    iv. After receiving message from the client it sends a 200 OK response to the client.
    2. Sender:
    i. Sends a SIP message to a particular URI (say [email protected]:5060)
    ii. Waits for the 200 OK response from the receiver.
    iii. When it receives the response displays something meaningful.
    The receiver is performing all the tasks, i.e. receiving msg from the Sender and sending the 200 OK response back to the Sender. BUT the Sender (i.e. the client) sends the msg to the receiver (which is perfectly received by the Receiver) but fails to receive the response from the receiver.
    So anybody could please explain what is the exact problem as the Sender fails to receive the response from the Receiver.
    Note: I am not testing my own code, I am testing the SIPDemo provide with the WTK2.5 simulator. I am also attaching the source code here:
    * Copyright � 2006 Sun Microsystems, Inc. All rights reserved.
    * Use is subject to license terms.
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.sip.*;
    public class SIPDemo extends MIDlet implements CommandListener {
        private static final String appTitle = "SIP Demo";
        private String sipAddress = "[email protected]";
        private int portReceive = 5070;
        private int portSend = 5070;
        private String message = "Some Message Body";
        private String msgSubject = "Test Message";
        private Display display;
        private Form form = new Form(appTitle);
        private List list;
        private Command goCommand = new Command("Go", Command.ITEM, 1);
        private Command exitCommand = new Command("Exit", Command.EXIT, 0);
        private Command sendCommand = new Command("Send", Command.OK, 1);
        private Command receiveCommand = new Command("Receive", Command.OK, 1);
        private TextField tfAddress;
        private TextField tfPort;
        private TextField tfSubject;
        private TextField tfMessage;
        private SipClientConnection sc = null;
        private SipConnectionNotifier scn = null;
        private SipServerConnection ssc = null;
        public SIPDemo() {
            super();
            display = Display.getDisplay(this);
            initList();
            display.setCurrent(list);
        private void initList() {
            list = new List(appTitle, Choice.IMPLICIT);
            list.append("Send Message", null);
            list.append("Receive Message", null);
            list.addCommand(exitCommand);
            list.addCommand(goCommand);
            list.setCommandListener(this);
        private void composeMessage() {
            tfAddress = new TextField("Address ", sipAddress, 50, TextField.LAYOUT_LEFT);
            tfPort = new TextField("Port ", String.valueOf(portSend), 6, TextField.LAYOUT_LEFT);
            tfSubject = new TextField("Subject ", msgSubject, 50, TextField.LAYOUT_LEFT);
            tfMessage = new TextField("Message Body ", message, 150, TextField.LAYOUT_LEFT);
            form.append(tfAddress);
            form.append(tfPort);
            form.append(tfSubject);
            form.append(tfMessage);
            form.addCommand(sendCommand);
            form.addCommand(exitCommand);
            form.setCommandListener(this);
            display.setCurrent(form);
        public void receiveMessage() {
            tfPort = new TextField("Port ", String.valueOf(portReceive), 6, TextField.LAYOUT_LEFT);
            form.append(tfPort);
            form.addCommand(receiveCommand);
            form.addCommand(exitCommand);
            form.setCommandListener(this);
            display.setCurrent(form);
        public void receiveTextMessage() {
            Thread receiveThread = new ReceiveThread();
            receiveThread.start();
        public void commandAction(Command c, Displayable s) {
            if (c == exitCommand) {
                destroyApp(true);
                notifyDestroyed();
            } else if (((s == list) && (c == List.SELECT_COMMAND)) || (c == goCommand)) {
                int i = list.getSelectedIndex();
                if (i == 0) { // Send Msg
                    composeMessage();
                } else if (i == 1) { // Receive Msg
                    receiveMessage();
            } else if (s == form) {
                if (c == sendCommand) {
                    message = tfMessage.getString();
                    msgSubject = tfSubject.getString();
                    sipAddress = tfAddress.getString();
                    portSend = getPort(tfPort.getString());
                    if (portSend == -1) {
                        return;
                    sendTextMessage(message);
                } else if (c == receiveCommand) {
                    portReceive = getPort(tfPort.getString());
                    if (portReceive == -1) {
                        return;
                    form.deleteAll();
                    form.removeCommand(receiveCommand);
                    receiveTextMessage();
         * Converts ASCII to int and ensures a positive number.
         * -1 indicates an error.
        public int getPort(String s) {
            int i = -1;
            try {
                i = Integer.valueOf(s).intValue();
            } catch (NumberFormatException nfe) {
                // don't do anything, the number will be -1
            if (i < 0) {
                Alert alert = new Alert("Error");
                alert.setType(AlertType.ERROR);
                alert.setTimeout(3000); // display the alert for 3 secs
                alert.setString("The port is not a positive number.\n" +
                    "Please enter a valid port number.");
                display.setCurrent(alert);
                return -1;
            return i;
        public void startApp() {
            System.out.println("Starting SIP Demo...\n");
        public void sendTextMessage(String msg) {
            SendThread sendThread = new SendThread();
            sendThread.start();
        public void destroyApp(boolean b) {
            System.out.println("Destroying app...\n");
            try {
                if (sc != null) {
                    System.out.println("Closing Client Connection...");
                    sc.close();
                if (ssc != null) {
                    System.out.println("Closing Server Connection...");
                    ssc.close();
                if (scn != null) {
                    System.out.println("Closing Notifier Connection...");
                    scn.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                notifyDestroyed();
        public void pauseApp() {
            System.out.println("Paused...\n");
        /** Send Message Thread */
        class SendThread extends Thread implements SipClientConnectionListener {
            private int recTimeout = 0; // do not wait, just poll
            public void notifyResponse(SipClientConnection sc) {
                try {
                    sc.receive(recTimeout);
                    form.append("Response received: " + sc.getStatusCode() + " " +
                        sc.getReasonPhrase());
                    sc.close();
                } catch (Exception ex) {
                    form.append("MIDlet: exception " + ex.getMessage());
                    ex.printStackTrace();
            public void run() {
                try {
                    sc = (SipClientConnection)Connector.open("sip:" + sipAddress + ":" + portSend);
                    sc.setListener(this);
                    sc.initRequest("MESSAGE", null);
                    sc.setHeader("From", "sip:" + sipAddress);
                    sc.setHeader("Subject", msgSubject);
                    sc.setHeader("Content-Type", "text/plain");
                    sc.setHeader("Content-Length", Integer.toString(message.length()));
                    OutputStream os = sc.openContentOutputStream();
                    os.write(message.getBytes());
                    os.close(); // close the stream and send the message
                    form.deleteAll();
                    form.removeCommand(sendCommand);
                    form.append("Message sent...\n");
                } catch (IllegalArgumentException iae) {
                    Alert alert = new Alert("Error");
                    alert.setType(AlertType.ERROR);
                    alert.setTimeout(3000); // display the alert for 3 secs
                    alert.setString("Some of the submitted data is invalid.\n" +
                        "Please enter valid information.");
                    display.setCurrent(alert);
                } catch (Exception ex) {
                    form.append("MIDlet: exception " + ex.getMessage());
                    ex.printStackTrace();
        /** Receive Message Thread */
        class ReceiveThread extends Thread {
            private byte[] buffer = new byte[0xFF];
            public void run() {
                try {
                    scn = (SipConnectionNotifier)Connector.open("sip:" + portReceive);
                    form.append("Listening at " + portReceive + "...");
                    // block and wait for incoming request.
                    // SipServerConnection is established and returned
                    // when a new request is received.
                    ssc = scn.acceptAndOpen();
                    if (ssc.getMethod().equals("MESSAGE")) {
                        String contentType = ssc.getHeader("Content-Type");
                        if ((contentType != null) && contentType.equals("text/plain")) {
                            InputStream is = ssc.openContentInputStream();
                            int bytesRead;
                            String msg = new String("");
                            while ((bytesRead = is.read(buffer)) != -1) {
                                msg += new String(buffer, 0, bytesRead);
                            form.append("\n...Message Received\n");
                            form.append("Subject: \"" + ssc.getHeader("Subject") + "\"\n");
                            form.append("Body: \"" + msg + "\"\n\n");
                        // initialize SIP 200 OK and send it back
                        ssc.initResponse(200);
                        ssc.send();
                        form.append("Response sent...\n");
                    ssc.close();
                } catch (Exception ex) {
                    // IOException
                    // InterruptedIOException
                    // SecurityException
                    // SipException
                    form.append("MIDlet: exception " + ex.getMessage());
                    ex.printStackTrace();
    }

    I am having exactly the same problem!!!!
    In fact I developed days ago an application with SUBSCRIBE and NOTIFY messages, with the J2ME client as the receiver of NOTIFY requests... the requests arrived, but the responses, once sent, never get to the NOTIFY sender.
    I asked this same question in the following forum:
    http://forum.java.sun.com/forum.jspa?forumID=82
    but at this moment nobody replies...
    Today I was checking the SIPDemo implementation in SWTK2.5, and what was my surprise when I worked out that the implementation gave the same problem... I have tried several settings modifications in the SWTK preferences and settings, but no success.
    Please, is anybody aware of how to resolve this problem??, I really need the answer.
    Ashgar... do you know where can the problem be??

  • WTK http stack implementation bug: malformed URL

    Hi
    the WTK emulators dont parse URLs correctly. The following code throws an "java.lang.IllegalArgumentException: malformed URL" exception. It works on most phones and the SonyEricsson J2ME SDK tho.
    c = (HttpConnection) Connector.open("http://www.4950.net");
    The stack trace is
    java.lang.IllegalArgumentException: malformed URL
         at com.sun.midp.io.HttpUrl.isIPv4Address(+88)
         at com.sun.midp.io.HttpUrl.parseAfterScheme(+568)
         at com.sun.midp.io.HttpUrl.<init>(+36)
         at com.sun.midp.io.j2me.http.Protocol.connect(+18)
         at com.sun.midp.io.ConnectionBaseAdapter.openPrim(+52)
         at javax.microedition.io.Connector.openPrim(+299)
         at javax.microedition.io.Connector.open(+15)
         at javax.microedition.io.Connector.open(+6)
         at javax.microedition.io.Connector.open(+5)
    I interpret the error as the http stacks recognizing this url as a numbered notation (e.g. http://123.234.34.24) instead of a text notation (e.g. http://www.google.com).
    I tried to look into the midp sources but the ones that are online do not contain the method com.sun.midp.io.HttpUrl.isIPv4Address from reading the source available it seems that the midp2.0fcs sources dont contain this error.
    Can anyone in sun fix this?

    an URL cannot start with a number after the www !

  • Implementing Service Stack with SAPEHPI

    Hi,
    I've read that it's possible to implement only Service Stacks (without EHP) in SAP NetWeaver ABAP Systems with the EHP Installer.
    I also got the information that it's much faster than the SPAM transaktion.  
    Can anyone tell me if there is a guide for this?  Or has someone done it already?   Where is the technical advantage to the implemenation via SPAM?
    Thanks a lot for your responses.
    BR,
    Andreas

    Hello Andreas,
    Its very well possible to use EHPi to apply support packages.
    check this link :
    The specified item was not found.
    and follows following point, i am pasting the important content.
    New features and Improvements
    All the features below are also described in the Installation Guide for SAP enhancement package installations:
    Using SAPehpi to apply Support Package Stacks on ABAP-only systems: You can use SAPehpi to apply Support Package Stacks to your ABAP-only system, even if you do not install an enhancement package. Using SAPehpi for Support Package Stacks-only you can benefit significantly unsing the SAPehpi System Switch Technology for a larger number of Support Packages. With the new procedure you can benefit from a downtime and risk mitigation approach compared to Support Package Stack implementation via Transaction SPAM (Support Package Manager).
    Note: This scenario is currently only released for ABAP-only systems.
    Previously this was released as pilot for some customers but now i think its available for all. Did u checked the options in the new EHPi ? although i haven't used this option till now so i am not sure if its available from 7.00 or 7.1.
    But u can just check the options in the EHPi. I'll check and if i found something i'll let u know.
    in the above link there is the link for the pilot run as well, do follow that also.
    Best Regards
    Niraj

  • Problem with Stack

    Hi,
    I need a stack implementation of an stack. I found some code on http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/10_objs.htm (see chapter Object Type Example: Stack), but I don't know how to handle it.
    When I try
    declare
      s Stack;
    begin
      s.INITIALIZE;
    end;I get an ORA-30625
    ORA-30625: Methoden-Dispatch mit Argument NULL SELF ist nicht zulässig
    ORA-06512: in Zeile 4can somebody please help me and show me where's the problem or how I have to handle this object?
    Thanks

    can somebody please help me and show me where's the problem or how I have to handle this object?
    SQL>  create type intarray as varray (25) of integer;
    Type created.
    SQL>  create type stack as object (
       max_size   integer,
       top        integer,
       position   intarray,
       member procedure initialize
    Type created.
    SQL>  create type body stack
    as
       member procedure initialize
       is
       begin
          top := 0;
          /* call constructor for varray and set element 1 to null. */
          position := intarray (null);
          max_size := position.limit;               -- get varray size constraint
          position.extend (max_size - 1, 1);         -- copy element 1 into 2..25
       end initialize;
    end;
    Type body created.
    SQL>  declare
       s   stack := stack (null,null,null);
    begin
       s.initialize;
    end;
    PL/SQL procedure successfully completed.

  • Stack Class

    Hello.
    I'm trying to implement a stack class, where the stack only holds boolean values, and will have a maximum size of about 32.
    I've designed an interface which looks like:
    public interface IBooleanStack {
        public void push(Boolean b);
        public Boolean pop();
        public Boolean top();
        public boolean isEmpty();
        public void clear();
        public int size();
    }What would you suggest would be the best way to implement this? Should I use an array, or the built-in stack?
    The reason I ask is that if I were to use the built-in stack implementation, would that not make my push() and pop() methods redundant? I have to use them, which is why I was considering other options.
    Thanks :)
    Edited by: chrisdb89 on Oct 29, 2008 4:09 AM

    Thank you all for your advice.
    I got the arrayStack to work, so that's good.
    I also implemented an sllStack, basically the same way, however when I pop anything from the stack, it always returns null.
    I'm importing the following:
    package uk.ac.stand.cs.cs2001.Prac05.sll;
    public class SLLNode {
         public Boolean b;
         public SLLNode next;
         public SLLNode (Object element, SLLNode next) {
         this.b = b;
         this.next = next;
    }and here is my implementation of the SLL:
    package uk.ac.stand.cs.cs2001.Prac05.impl;
    import uk.ac.stand.cs.cs2001.Prac05.interfaces.IBooleanStack;
    import uk.ac.stand.cs.cs2001.Prac05.sll.SLLNode;
    public class SLLStack implements IBooleanStack {
         private SLLNode root;
         private int current_size;
         public SLLStack() {
              root = null;
              current_size = 0;
         public void push(Boolean b) {
              root = new SLLNode(b, root);
              current_size++;
         public Boolean pop() {
              if (!isEmpty()) {
                   Boolean b = root.b;
                   root = root.next;
                   current_size--;
                   return b;
              } else {
                   throw new IllegalStateException("Error: Stack is full.");
         public Boolean top() {
              if (!isEmpty()) {
                   return root.b;
              } else {
                   throw new IllegalStateException("Error: Stack is full.");
         public int size() {
              return current_size;
         public boolean isEmpty() {
              return root == null;
         public void clear() {
              root = null;
              current_size = 0;
         public static void main(String[] args) {
              IBooleanStack sllStack = new SLLStack();
              sllStack.push(true);
              System.out.println("'True' added to stack.\n");
              sllStack.push(false);
              System.out.println("'False' added to stack.\n");
              while (!sllStack.isEmpty()) {
                   System.out.println(sllStack.pop());
    }Can anybody tell me what I'm missing? Any help will be greatly appreciated.
    We haven't covered DLL in class, so I don't think I should use that implementation for this :)
    Thanks again.
    Chris

  • Is SAP PO 7.4 dual stack installation??

    HI experts,
    Could anyone let me know if SAP PO 7.4 is a dual stack installation or can we go for single stack as well.
    As PI 7.4 is based on HANA , so while working on it shall we use ICO or old classic configuration. Shall we go for java based adapters(eg IDOC_AAE/HTTP_AAE)  or old abap based adapter..
    Thanks,

    To add few cents - May be your basis guys just read the title
    Support for Dual-Stack discontinued in SAP NetWeaver 7.4 in general with exceptions
    SAP NetWeaver 7.4 is positioned as the follow-up on-premise release for SAP NetWeaver 7.31.
    SAP NetWeaver is among other things optimized for SAP HANA as the foundation for the SAP Business
    Suite on SAP HANA project. This means that dual-stack deployments and implementations are not
    supported any longer. The only exception to this rule is SAP NetWeaver Process Integration on a traditional
    database system, which still requires a dual-stack implementation. However, note that a single-stack SAP
    NetWeaver Process Integration Java exists that offers 95% of the features of classical dual-stack
    implementations. Therefore, customers should investigate whether an existing SA
    Reference : http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/60bf3650-e219-3010-ef93-d11928aa8f8a?QuickLink=index&…

  • How to access a Stack class from different classes

    Hi
    I have a Stack implemented as Stack.java. I have 2 more java files Control.java and display.java.
    In Control.java
    I have created Stack stack = new Stack(); and am pushing values in the stack.
    In display.java i have some conditions where i want to push some values in the same stack as that on the Control.java.
    How do i acces the stack in Control.java from other files like display.java

    In display.java i have some conditions where i want
    to push some values in the same stack as that on the
    Control.java.
    How do i acces the stack in Control.java from other
    files like display.javaPass that object reference to some method. :-)

  • Implementation of depth-first algorithm

    Hi, I am trying to implement depth-first algorithm.(directed graph, no loops). Here what I have so far.
    //form a one-element stack with the root node.
    Stack st=new st();
    boolean goalflg=false;
    st.push(?)//do I need to clone the value from the tree, if yes, how can I do this? Should it be a Spanning Tree or not?
    //repeat until the first path in the stack terminates at the goal node or the stack is empty
    while(st.size()!=null || goalflg == true){  
    /*-remove the first math from the Stack;create new paths by extending the first path to all neighbors of the terminal node * /
    int temp=st.pop();
    nodeRight=tree.goRight();// I aren't sure nodeLeft=tree.goLeft();
    //reject all new paths with loops (how can I do this?)
    //if the goal is found-success, else -failure     
    if (temp==goalNode)     
    {goalflg=true;}     
    else{        //add the new paths to the front of stack      
    st.push(nodeRight);
    st.push(nodeLeft);     
    Please,please help!
    Sincerely,
    Byryndyk
    P.S. I check out google, but it has mostly the theory about this method. What I am interested is how to make it alive.

    This algorithm for DFS has no constraints on edges as it works purely by inspecting adjacency lists; if a directed edge, e, goes from vertex u to vertex v, then v is adjacent to u, but u is not adjacent to v i.e. you can not travel this edge from v to u.
         public VertexModelInterface[] depthFirstSearch(VertexModelInterface from)
              visited.add(from);
              VertexModelInterface[] adjacencyList = (VertexModelInterface[]) from.getAdjacencyList().toArray(new VertexModelInterface[0]);
              for (int index = 0; index < adjacencyList.length; index++)
                   if (!visited.contains(adjacencyList[index]))
                        depthFirstSearch(adjacencyList[index]);
                   } // end if
              } // end for
              return (VertexModelInterface[]) visited.toArray(new VertexModelInterface[0]);
         } // end depthFirstSearch
    visited is a list containing vertices. Each vertex has an adjacency list containing references to adjacent vertices.
    Hope this helps anyone whos looking for a neat recursive (implicit stack) implementation. I also have implementations for BFS, Cut-Edge-Detection and Fleury's algorithm.
    Kind regards,
    Darren Bishop.
    [email protected]

  • Need help with Stacks

    Hi all,
    I'm writing a parser that reads a file, looks for tags and adds them to a stack when an opening tag is found, i.e. <html>.
    When a closing tag is found (i.e. </html>) I want to compare this tag with the tag at the top of the stack, and if they match, then remove it.
    I haven't explained it very well which I apologise for, and I'm sure the answer is very simple, but I'm quite stuck and would greatly appreciate any help.
    I've missed out some of the code that is irrelevant.
    Stack.java
    public class Stack {
        private String[] stackArray;
        private int top;
        private int maxSize = 30;
        public Stack(int s)                    //constructor
            stackArray = new String[maxSize];
            top = -1;
        public void push(String j)                     //add to top of stack
            stackArray[++top] = j;
        public String pop()                            //remove from top of stack
            return stackArray[top--];
        public boolean isEmpty()                     //see if stack is empty (will return true)
            return (top == -1);
        public String peek()
            System.out.println("At the top of the stack is: " + stackArray[top] + "\n");
            return stackArray[top];
    }And this works with
    AFileReader.java
    package MyProject;
    import java.io.*;
    public class AFileReader {
        String fileName;
        StringBuffer tagName;
        boolean inTag = false;
        public void setFilename(String inFileName)
            fileName = inFileName;
        public void scanFile()
            try{                        //open file
                FileInputStream fstream = new FileInputStream(fileName);
                int readInt;
                char inChar;
                Stack stack = new Stack(40);
                while ((readInt = fstream.read()) != -1)     //start of loop
                    Thread.sleep(50);
                    inChar = (char)readInt;
                    if (inChar == '<')
                        inTag = true;
                        tagName = new StringBuffer();
                    else if (inChar == '>')
                        inTag = false;             //end of tag
                        System.out.print(tagName + "\n");
                        if ((tagName.toString()).contains("/") &&                   //if tag contains a '/'
                                (!(tagName.toString()).endsWith("/")) &&            //but it isn't at the end
                                      (!(tagName.toString()).startsWith("/")))      //or start of tag
                            System.out.println("Error in tag. \n");             //there is no legal place for it
                        else if ((tagName.toString()).endsWith("/"))            //self closing tags (i.e. <br/>
                            System.out.println("Self-closing tag - no action required. \n");
                        else if (tagName.charAt(0) != '/')                      //normal opening tags
                            System.out.println("Tag found. Adding to stack... \n");
                            stack.push(tagName.toString());                     //push onto stack
                        else if (tagName.charAt(0) == '/')                      //tags beginning with '/' are closing
                            System.out.println("Closing tag found.");
                            stack.peek();
                    else
                            if (inTag = true)
                                    tagName.append(inChar);
            catch(NullPointerException npe)
                npe.getMessage();
            catch(FileNotFoundException e)
                System.err.println("FileNotFoundException: " + e.getMessage());
            catch(IOException ioe)
                System.err.println("IOException: " + ioe.getMessage());
            catch (Exception e)
                e.getMessage();
    }

    Well this is syntactically invalid:
                    if (inChar == '<'>')But I have no idea if that's what you meant. You didn't really say what the problem is. Are you just not able to compile?
    By the way, you realize that you're duplicating existing tools, right? If this isn't a homework assignment, then you're going about it the wrong way -- there's already a Stack implementation and you can use SAX to tokenize the HTML if it's XHTML.

  • Multi-threaded stack

    Hello,
    Fisrt of all, I am sorry that I post such a noobish question which, I am confident, has been resolved in a number of times, but I was unable to Google the answer.
    Here's the problem:
    I have a array-based stack implementation that takes ints.
    The Push method adds the value to the next empty "slot", or waits (wait() method) if the stack is full.
    The Pop method removes the last value, or waits if the stack is empty.
    Both methods calls notifyAll() in the end - so adding value would wake up "poppers" and removing value would wake up "pushers".
    Now I have this stack and 3 pushers and 3 poppers, each running in its own thread. The stack capacity is limited (10 in my case). Each pusher will push 100 random values. The problem is that pushers will push theirs 100 values and end, but when this happens and all values are popped, poppers would wait indefinetly for more values (so theirs threads would never die).
    The problem I am stuck with is when I enter the Pop() method, I am bound to return a value, but if no more values are going to occur, I dont know what to return - and I dont want to throw an exception.
    TY for answer

    1) It should not. It is an universal stack that should not care what is going on anywhere else.
    2) The first answer renders this question irrelevant.
    I am enclosing the source:
    class Popper extends Thread
         private Stack stack;
         private String name;
         Popper(Stack stack, String name) {
              this.stack = stack;
              this.name = name;
         public void run() {
              while(true){
                   int value = stack.pop();
                   System.out.println(name + " popped " + value);
                   stack.printout();
    class Pusher extends Thread
         private java.util.Random generator;
         private Stack stack;
         private String name;
         public Pusher(Stack stack, String name) {
              this.stack = stack;
              this.name = name;
              generator = new java.util.Random();
         public void run() {
              for (int i = 0; i < 10; i++) {
                   int rand = generator.nextInt(20);
                   stack.push(rand);
                   System.out.println(name + " pushed " + rand);
                   stack.printout();
    class Stack
         private boolean full;
         private boolean empty = true;
         private int[] stack;
         private int currentIndex;
         public Stack(int capacity) {
              stack = new int[capacity];
         public synchronized void push(int value){
              while (full){
                   try {
                        wait();
                   } catch (InterruptedException e) {e.printStackTrace();}
              stack[currentIndex++] = value;
              empty = false;
              if(currentIndex >= stack.length) full = true;
              notifyAll();
         public synchronized int pop (){
              while(empty){
                   try {
                        wait();
                   } catch (InterruptedException e) {e.printStackTrace();}
              int value = stack[--currentIndex];
              stack[currentIndex] = 0;
              full = false;
              if(currentIndex == 0) empty = true;
              notifyAll();
              return value;
         public void printout(){
              StringBuilder builder = new StringBuilder();
              for(int i = 0; i < stack.length; i++){
                   builder.append(stack[i] + ", ");
              System.out.println(builder.toString());
    class Start
         public static void main(String[] args) {
              Stack stack = new Stack(10);
              Pusher pusher = new Pusher(stack, "Pusher 1");
              Pusher pusher2 = new Pusher(stack, "Pusher 2");
              Pusher pusher3 = new Pusher(stack, "Pusher 3");
              Popper popper = new Popper(stack, "Popper 1");
              Popper popper2 = new Popper(stack, "Popper 2");
              Popper popper3 = new Popper(stack, "Popper 3");
              pusher.start();
              pusher2.start();
              pusher3.start();
              popper.start();
              popper2.start();
              popper3.start();
    }Try to run the code for urself. At the end, the three poppers will be waiting in the pop() method indefinetly, so the program will never terminate. I want to chage this code so that the program will terminate when no more pushes will occur and the stack is empty.
    Edited by: Shagrat on Mar 3, 2010 11:47 AM

  • Search for RFCOMM implementation

    Hi, I'm developping some apps. for transferring files from a Set-top-box to a cell phone.
    The STB runs JavaTV, with no BT stack implementation (no BT hardware too), but I'm managing to attach a serial BT dongle to it and run the JavaBluetooth (javabluetooth.org) stack over it.
    Currently I'm runing the JavaBT on a PC, but the RFCOMM and other high-level layers were not implemented on this stack.
    I need only the an outputStream (SPP) over the BT link, wich is implemented in the RFCOMM layer.
    JavaBluetooth currently supports L2CAP, fully as far as I know, so before starting to write an RFCOMM over the L2CAP layer provided I'm searching for some code already builded.
    Does anyone knows where can I get the sources from a RFCOMM implementation over a JSR82 L2CAP connection.
    any ideas may help, thanks

    Hi,
    I am working with the Minshara, but I find it like a black box.. nothing is transperant except the RFCOMM layer. They had infact built the entire RFCOMM on top of the javabluetooth.org.
    There is the BCC implementation as recommended by the JSR-82 spec. I tried to discover devices and services, it does it although a bit of work around is needed.
    I was able to retrive the serviceURL which is supposed to open a StreamConnection. I am stuck at this point. It just hangs up there. doesnt open me a StreamConnection.
    Would be nice to know if there is anyone who had tried this.
    Cheers
    Domnic

Maybe you are looking for

  • Is the Sites folder included in Time Machine backups?

    I've learned the hard way that not everything is included in a Time Machine backup.  For example, if you have iPhoto open, a backup will not be made of the photos.  Now that I'm developing websites and storing them in the Sites folder, is it safe to

  • I installed a cooling fan in my G3

    My hard drive died so I put a new one in (80gb, 7200 rpm) and I thought it would be a good time to install a cooling fan. I put an 80mm, 30cfm fan just under the exhaust vent on top of the iMac, and powered it w/ the hard drive power cable (the fan h

  • How to implement the Seibel response in the ADF ?

    Hi All, JDev ver : 11.1.1.5 I have integrated the Fusion middle ware with Seibel using the 'REST' services(The URI based service). I followed this link to integrate : http://siebel-essentials.blogspot.com/2011/02/first-encounter-with-sai-ofm.html I w

  • Is it possible to create an Apple Script to import data from a web data feed (RESTful XML/JSON)?

    Before I get started looking for a programmer, does anyone know if it will be possible to create a script that will allow Numbers to connect to an external data feed in either XML or JSON? I want to enable some colleagues who use Mac to connect to th

  • Vendor evaluation points automatic criteria

    Hi How the percencetage & points are determined for automatic criteria. Regards Umapathy