Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 36

Thread: Using Stacks Homework Help

  1. #1
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Using Stacks Homework Help

    I will go ahead and apologize for the massive code slice, but I am stuck on a problem. The code compiles and runs, but is not acting properly. I have tried to comment as best I can throughout the code so you know whats going on. I also have a comment at the very bottom of the code snippet that is the output of the trial run and what is wrong. Basically i am suppose to read in a text file containing some programming code from any language and make sure that for every opening bracer I.E. " { ", " [ " , " ( " it has a matching closing bracer. Meaning there is no syntax error. Basically the head element on the stack should be matching up to its counterpart when the code checks these elements. Problem is it won't throw an error when given a file that doesn't contain proper syntax but its not printing out the elements in the stack either before it goes into the checking process (the second time through the file), likewise when given a code with proper syntax such as the example i give at the bottom of the code, it compiles, runs, and prints out the original code no problem, but it is skipping the step where it is supposed to print out the elements being held in the stack prior to the check. Thanks in advance for any help. My main concern is getting the stack to print out what its holding first, and I'm at a loss for why it's not, after that is working we can move on to why it is not throwing an error when given incorrect code, but I'm thinking they may go hand in hand, since the stack is apparently holding nothing it is comparing nothing, so the code thinks it's fine.

    /*
     * A Java program can have the following type of delimiters: {, }, (, ), [, 
     * and ]. In a correct Java program, these delimiters must be properly nested. 
     * Think of each left delimiter {, (, and [ as opening a scope, and think of 
     * each right delimiter }, ), and ] as closing a scope opened by a corresponding
     * left delimiter. A string of characters containing these delimiters has proper
     * nesting of delimiters if each scope that is opened is eventually closed, and 
     * the scopes are opened and closed in a last-opened-first-closed fashion.
     
    * Write a program, using your own stack and/or queue code, that reads a file 
    * containing Java source code and checks it for proper nesting of delimiters.
    * Your program should read the source code from the file and print it to the
    * screen. If the file is properly nested, all of it is printed to the screen 
    * and a message is printed that the file is properly nested. If the file is 
    * not properly nested, then copying of the file to the screen stops as soon 
    * as improper nesting is detected, and your program prints a message that the 
    * file has errors. To simplify your task, you may assume these delimiters do
    * not appear inside of comments and string literals, and that they do not 
    * appear in the program as character literals--i.e. only appear as "keywords".
    * 
    * Name: Phillip Vinson
    * Project: Checking Code text file for proper syntax braces
    * Date: 03/12/2013
     */
     
    package hw4vinson;
     
    import java.io.*;
    import java.util.*;
     
    //Stack class, using linked list format
    public class HW4Vinson 
    {
        public class Node
        {
            String value;
            Node next;
            Node(String val, Node n)
            {
                value = val;
                next = n;
            }
        }
     
        public Node top = null; //Top of stack
     
        //checks to see if the stack is empty
        public boolean empty()
        {
            return top == null;
        }
     
        //adds a node/element to the stack
        public void push(String s)
        {
            top = new Node(s, top);
        }
     
        //removes the head node/element from the stack, throws error if stack is empty
        public String pop()
        {
            if (empty())
            {
                throw new EmptyStackException();
            }
            else
            {
                String retValue = top.value;
                top = top.next;
                return retValue;
            }
        }
     
        //returns the head node/element from the stack, throws an error if empty
        public String peek()
        {
            if (empty())
            {
                throw new EmptyStackException();
            }
            else
            {
                return top.value;
            }
        }
     
        //Main program
        public static void main(String[] args) 
        {
            String temp;    //store syntax
            String fileName;    //var to hold user input from keyboard
            Scanner kb = new Scanner(System.in);    //Get user input
            System.out.println("Enter a file to be read: (EX: file.txt)");
            fileName = kb.nextLine();   //Store user input from keyboard
     
            //Create a stack/linked list
            HW4Vinson st = new HW4Vinson();
     
            //What To Do:
            //1. Read in a text file and store all instances of {, [, (
            //   into the stack
            //2. Reread and print the text file, but compare the stack contents with
            //   each }, ], ) and make sure it matches.  
            //3. For instance if you read in
            //   {, {, (, {  then your pop should match with }, ), }, }
            //4. If it does not then stop the text print at the instance of bad read
            //   and display an error message stating the error and which delimeter
            //   is missing.
            //5. If no errors are found the entire text file should print
     
            try
            {
                //Open user designated file
                FileInputStream fstream = new FileInputStream(fileName);
                //Prepare files
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
     
                //Read file line by line
                while((strLine = br.readLine()) != null)
                {
                    System.out.println(strLine);
     
                    //check for symbol matches on each line and push onto stack
                    if("{".equals(strLine) || "[".equals(strLine) || "(".equals(strLine))
                    {
                    //push matching symbols onto our st stack
                        if ("{".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                        }
                        else if ("[".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                        }
                        if ("(".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                        }
                    }
                }
                //close the input stream
                in.close();
            }
            catch(Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }   
     
            //Print out all the elements being stored in the stack for
            //error checking
            System.out.println("\nElements in stack:");
            System.out.println(st);
            System.out.println("\n\n"); //skip a few lines
     
     
    //---------------------------------------------------------------------------//
    //---------------------------------------------------------------------------//
    //---------------------------------------------------------------------------//
     
            //Read file again to check for any erros in syntax
            try
            {
                //reopen user designated file
                FileInputStream fstream = new FileInputStream(fileName);
                //Prepare files
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
     
                //Read file line by line
                while((strLine = br.readLine()) != null)
                {
                    System.out.println(strLine);    //print out the code being stored
     
                    //check for symbol match
                    if("}".equals(strLine))
                    {
                        String holder = st.pop();   //pop and store head element
     
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("(".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("[".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
     
                    //check for symbol match on "]"
                    else if("]".equals(strLine))
                    {
                        String holder = st.pop();   //pop and store head element
     
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("{".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("(".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
     
                    //check for symbol match
                    else if(")".equals(strLine))
                    {
                        String holder = st.pop();  //pop and store head element
     
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("{".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("[".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
                }
                //close the input stream
                in.close();
            }
            catch(Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }    
        }
    }

    /*
    This is the file i'm using to test code:

    while (x == 32)
    {
    s = 34;
    if (s == 34)
    {
    s = s-1;
    }
    }


    running the above text file i get the output:

    run:
    Enter a file to be read: (EX: file.txt)
    correctFile.txt

    Elements in stack:
    hw4vinson.HW4Vinson@8a64642



    while (x == 32)
    {
    s = 34;
    if (s == 34)
    {
    s = s-1;
    }
    }
    BUILD SUCCESSFUL (total time: 4 seconds)


    Obviously this is not correct, it should print out all the values being stored
    in the stack first (apparently none based off the run), and then go through
    and perform a syntax check,if no errors are found it will just print the code
    to the screen (like it did)
    */
    Last edited by Norm; March 12th, 2013 at 07:47 PM. Reason: Moved the /code tag


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Can you post the output from when you execute the program that shows what it does?
    Add a println() that prints out the lines (strLine) as they are read from the file so we can see what the program was reading.

    Suggestion for debugging stacks/linked lists: Add a toString() method to the Node class and the stack class.
    The Node class returns the value and next. The stack class's toString() should return the link to the first node using its toString() method: return top.toString()
    This will show you what is in the stack.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    After adding a print statement right below the code
    while((strLine = br.readLine()) != null)
                {
    during the first read file cycle it prints out:


    run:
    Enter a file to be read: (EX: file.txt)
    correctFile.txt
    while (x == 32)
    {
    s = 34;
    if (s == 34)
    {
    s = s-1;
    }
    }

    Elements in stack:
    hw4vinson.HW4Vinson@8a64642



    while (x == 32)
    {
    s = 34;
    if (s == 34)
    {
    s = s-1;
    }
    }
    BUILD SUCCESSFUL (total time: 4 seconds)

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    We cross posted. See the end of my last post.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    Updated code is below, it seems it is holding a value in the stack which is good, we are getting a error null for some reason, but the code still runs, only other problem is it is only holding one of the elements not 4, should be in the order of intake " ( ", " { " , " ( " , " { " which means the pop is the opposite, but it should still be holding more than one element.

    /*
     * A Java program can have the following type of delimiters: {, }, (, ), [, 
     * and ]. In a correct Java program, these delimiters must be properly nested. 
     * Think of each left delimiter {, (, and [ as opening a scope, and think of 
     * each right delimiter }, ), and ] as closing a scope opened by a corresponding
     * left delimiter. A string of characters containing these delimiters has proper
     * nesting of delimiters if each scope that is opened is eventually closed, and 
     * the scopes are opened and closed in a last-opened-first-closed fashion.
     
    * Write a program, using your own stack and/or queue code, that reads a file 
    * containing Java source code and checks it for proper nesting of delimiters.
    * Your program should read the source code from the file and print it to the
    * screen. If the file is properly nested, all of it is printed to the screen 
    * and a message is printed that the file is properly nested. If the file is 
    * not properly nested, then copying of the file to the screen stops as soon 
    * as improper nesting is detected, and your program prints a message that the 
    * file has errors. To simplify your task, you may assume these delimiters do
    * not appear inside of comments and string literals, and that they do not 
    * appear in the program as character literals--i.e. only appear as "keywords".
    * 
    * Name: Phillip Vinson
    * Project: Checking Code text file for proper syntax braces
    * Date: 03/12/2013
     */
     
    package hw4vinson;
     
    import java.io.*;
    import java.util.*;
     
    //Stack class, using linked list format
    public class HW4Vinson 
    {
        public class Node
        {
            String value;
            Node next;
            Node(String val, Node n)
            {
                value = val;
                next = n;
            }
        }
     
        public Node top = null; //Top of stack
     
        //checks to see if the stack is empty
        public boolean empty()
        {
            return top == null;
        }
     
        //adds a node/element to the stack
        public void push(String s)
        {
            top = new Node(s, top);
        }
     
        //removes the head node/element from the stack, throws error if stack is empty
        public String pop()
        {
            if (empty())
            {
                throw new EmptyStackException();
            }
            else
            {
                String retValue = top.value;
                top = top.next;
                return retValue;
            }
        }
     
        //returns the head node/element from the stack, throws an error if empty
        public String peek()
        {
            if (empty())
            {
                throw new EmptyStackException();
            }
            else
            {
                return top.value;
            }
        }
     
        public String toString()
        {
            StringBuilder sBuilder = new StringBuilder();
            Node p = top;
            while(p != null)
            {
                sBuilder.append(p.value);
                p = p.next;
                if (p != null)
                {
                    sBuilder.append("\n");
                }
            }
            return sBuilder.toString();
        }
     
        //Main program
        public static void main(String[] args) 
        {
            String temp;    //store syntax
            String fileName;    //var to hold user input from keyboard
            Scanner kb = new Scanner(System.in);    //Get user input
            System.out.println("Enter a file to be read: (EX: file.txt)");
            fileName = kb.nextLine();   //Store user input from keyboard
     
            //Create a stack/linked list
            HW4Vinson st = new HW4Vinson();
     
            //What To Do:
            //1. Read in a text file and store all instances of {, [, (
            //   into the stack
            //2. Reread and print the text file, but compare the stack contents with
            //   each }, ], ) and make sure it matches.  
            //3. For instance if you read in
            //   {, {, (, {  then your pop should match with }, ), }, }
            //4. If it does not then stop the text print at the instance of bad read
            //   and display an error message stating the error and which delimeter
            //   is missing.
            //5. If no errors are found the entire text file should print
     
            try
            {
                //Open user designated file
                FileInputStream fstream = new FileInputStream(fileName);
                //Prepare files
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
     
                //Read file line by line
                while((strLine = br.readLine()) != null)
                {
                    //check for symbol matches on each line and push onto stack
                    if("{".equals(strLine) || "[".equals(strLine) || "(".equals(strLine))
                    {
                    //push matching symbols onto our st stack
                        if ("{".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                        }
                        else if ("[".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                        }
                        if ("(".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                        }
                    }
                }
                //close the input stream
                in.close();
                strLine.toString();
            }
            catch(Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }   
     
            //Print out all the elements being stored in the stack for
            //error checking
            System.out.println("\nElements in stack:");
            System.out.println(st);
            System.out.println("\n\n"); //skip a few lines
     
     
    //---------------------------------------------------------------------------//
    //---------------------------------------------------------------------------//
    //---------------------------------------------------------------------------//
     
            //Read file again to check for any erros in syntax
            try
            {
                //reopen user designated file
                FileInputStream fstream = new FileInputStream(fileName);
                //Prepare files
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
     
                //Read file line by line
                while((strLine = br.readLine()) != null)
                {
                    System.out.println(strLine);    //print out the code being stored
     
                    //check for symbol match
                    if("}".equals(strLine))
                    {
                        String holder = st.pop();   //pop and store head element
     
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("(".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("[".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
     
                    //check for symbol match on "]"
                    else if("]".equals(strLine))
                    {
                        String holder = st.pop();   //pop and store head element
     
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("{".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("(".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
     
                    //check for symbol match
                    else if(")".equals(strLine))
                    {
                        String holder = st.pop();  //pop and store head element
     
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("{".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("[".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
                }
                //close the input stream
                in.close();
            }
            catch(Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }    
        }
    }
     
     
    /*
    This is the file i'm using to test code:
     
    while (x == 32)
    {
    	s = 34;
    	if (s == 34)
    	{
    		s = s-1;
    	}
    } 
     
     
    running the above text file i get the output:
     
    run:
    Enter a file to be read: (EX: file.txt)
    correctFile.txt
     
    Error: null
    Elements in stack:
    {
     
     
     
    while (x == 32)
    {
    	s = 34;
    	if (s == 34)
    	{
    		s = s-1;
    	}
    }
    BUILD SUCCESSFUL (total time: 4 seconds)
     
     
    Obviously this is not correct, it should print out all the values being stored
    in the stack first (apparently none based off the run), and then go through 
    and perform a syntax check,if no errors are found it will just print the code 
    to the screen (like it did)
     */

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Time to do some debugging. Add some println() statements to print out what the code is doing and what the contents of the stack is after any change is made to it so you can see what the computer sees when the code is executed.


    Don't hide comments about the code's execution inside the code tags. Put the end tag after the last }

    Can you explain the logic of the program? For example: Why does it make two separate passes?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    how do you actually do the tag trick, i've never done that before. I will go through and add println()

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Can you explain the logic of the program? For example: Why does it make two separate passes?

    The tag trick? Are you talking about the location of the ending code tag? When you add it, put it at the end of the code, not after a bunch of comments.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    New code after adding print statements after every push or pop with the stack

    /*
     * A Java program can have the following type of delimiters: {, }, (, ), [, 
     * and ]. In a correct Java program, these delimiters must be properly nested. 
     * Think of each left delimiter {, (, and [ as opening a scope, and think of 
     * each right delimiter }, ), and ] as closing a scope opened by a corresponding
     * left delimiter. A string of characters containing these delimiters has proper
     * nesting of delimiters if each scope that is opened is eventually closed, and 
     * the scopes are opened and closed in a last-opened-first-closed fashion.
     
    * Write a program, using your own stack and/or queue code, that reads a file 
    * containing Java source code and checks it for proper nesting of delimiters.
    * Your program should read the source code from the file and print it to the
    * screen. If the file is properly nested, all of it is printed to the screen 
    * and a message is printed that the file is properly nested. If the file is 
    * not properly nested, then copying of the file to the screen stops as soon 
    * as improper nesting is detected, and your program prints a message that the 
    * file has errors. To simplify your task, you may assume these delimiters do
    * not appear inside of comments and string literals, and that they do not 
    * appear in the program as character literals--i.e. only appear as "keywords".
    * 
    * Name: Phillip Vinson
    * Project: Checking Code text file for proper syntax braces
    * Date: 03/12/2013
     */
     
    package hw4vinson;
     
    import java.io.*;
    import java.util.*;
     
    //Stack class, using linked list format
    public class HW4Vinson 
    {
        public class Node
        {
            String value;
            Node next;
            Node(String val, Node n)
            {
                value = val;
                next = n;
            }
        }
     
        public Node top = null; //Top of stack
     
        //checks to see if the stack is empty
        public boolean empty()
        {
            return top == null;
        }
     
        //adds a node/element to the stack
        public void push(String s)
        {
            top = new Node(s, top);
        }
     
        //removes the head node/element from the stack, throws error if stack is empty
        public String pop()
        {
            if (empty())
            {
                throw new EmptyStackException();
            }
            else
            {
                String retValue = top.value;
                top = top.next;
                return retValue;
            }
        }
     
        //returns the head node/element from the stack, throws an error if empty
        public String peek()
        {
            if (empty())
            {
                throw new EmptyStackException();
            }
            else
            {
                return top.value;
            }
        }
     
        public String toString()
        {
            StringBuilder sBuilder = new StringBuilder();
            Node p = top;
            while(p != null)
            {
                sBuilder.append(p.value);
                p = p.next;
                if (p != null)
                {
                    sBuilder.append("\n");
                }
            }
            return sBuilder.toString();
        }
     
        //Main program
        public static void main(String[] args) 
        {
            String temp;    //store syntax
            String fileName;    //var to hold user input from keyboard
            Scanner kb = new Scanner(System.in);    //Get user input
            System.out.println("Enter a file to be read: (EX: file.txt)");
            fileName = kb.nextLine();   //Store user input from keyboard
     
            //Create a stack/linked list
            HW4Vinson st = new HW4Vinson();
     
            //What To Do:
            //1. Read in a text file and store all instances of {, [, (
            //   into the stack
            //2. Reread and print the text file, but compare the stack contents with
            //   each }, ], ) and make sure it matches.  
            //3. For instance if you read in
            //   {, {, (, {  then your pop should match with }, ), }, }
            //4. If it does not then stop the text print at the instance of bad read
            //   and display an error message stating the error and which delimeter
            //   is missing.
            //5. If no errors are found the entire text file should print
     
            try
            {
                //Open user designated file
                FileInputStream fstream = new FileInputStream(fileName);
                //Prepare files
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
     
                //Read file line by line
                while((strLine = br.readLine()) != null)
                {
                    //check for symbol matches on each line and push onto stack
                    if("{".equals(strLine) || "[".equals(strLine) || "(".equals(strLine))
                    {
                    //push matching symbols onto our st stack
                        if ("{".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                            System.out.println(st);
                        }
                        else if ("[".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                            System.out.println(st);
                        }
                        if ("(".equals(strLine))
                        {
                            temp = strLine;
                            st.push(temp);
                            System.out.println(st);
                        }
                    }
                }
                //close the input stream
                in.close();
                strLine.toString();
            }
            catch(Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }   
     
            //Print out all the elements being stored in the stack for
            //error checking
            System.out.println("\nElements in stack:");
            System.out.println(st);
            System.out.println("\n\n"); //skip a few lines
     
     
    //---------------------------------------------------------------------------//
    //---------------------------------------------------------------------------//
    //---------------------------------------------------------------------------//
     
            //Read file again to check for any erros in syntax
            try
            {
                //reopen user designated file
                FileInputStream fstream = new FileInputStream(fileName);
                //Prepare files
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
     
                //Read file line by line
                while((strLine = br.readLine()) != null)
                {
                    System.out.println(strLine);    //print out the code being stored
     
                    //check for symbol match
                    if("}".equals(strLine))
                    {
                        String holder = st.pop();   //pop and store head element
                        System.out.println(st);
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("(".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("[".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
     
                    //check for symbol match on "]"
                    else if("]".equals(strLine))
                    {
                        String holder = st.pop();   //pop and store head element
                        System.out.println(st);
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("{".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("(".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
     
                    //check for symbol match
                    else if(")".equals(strLine))
                    {
                        String holder = st.pop();  //pop and store head element
                        System.out.println(st);
                        //if symbol coming off stack matches the improper syntax 
                        //throw error message
                        if("{".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                        else if("[".equals(holder))
                        {
                            //throw an error
                            System.out.println("Error Missing Syntax");
                        }
                    }
                }
                //close the input stream
                in.close();
            }
            catch(Exception e)
            {
                System.err.println("Error: " + e.getMessage());
            }    
        }
    }
     
     
    /*
    This is the file i'm using to test code:
     
    while (x == 32)
    {
    	s = 34;
    	if (s == 34)
    	{
    		s = s-1;
    	}
    } 
     
     
    running the above text file i get the output:
     
    run:
    Enter a file to be read: (EX: file.txt)
    correctFile.txt
    {
    Error: null
     
    Elements in stack:
    {
     
     
     
    while (x == 32)
    {
    	s = 34;
    	if (s == 34)
    	{
    		s = s-1;
    	}
    }
     
    BUILD SUCCESSFUL (total time: 4 seconds)
     
     
    Obviously this is not correct, it should print out all the values being stored
    in the stack first (apparently none based off the run), and then go through 
    and perform a syntax check,if no errors are found it will just print the code 
    to the screen (like it did)
     */


    --- Update ---

    sorry we cross posted again, it runs through the read twice, the first time it reads the text file and finds all the open bracers in the program and stores them in the stack. I then rerun the code and run a comparison between the stack and the closing bracers found anywhere in the code and make sure that if a " { " is being compared to a closing bracer it has to be a " } " if not it will throw an error

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Why does it make two passes? Many compilers do it in one pass.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    I wrote it for two haha, didn't know a way to make it read twice without opening the file and closing then reopening and closing.

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Look at doing it in one pass.

    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    I'll look into it, either way i'm still at a loss for why it's not finding all the parameters i'm looking for in the first pass. I don't think the second pass is effecting this at all.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Where does the code find any opening brackets, etc that are on a line with other characters?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    That would be the issue I am having, I can't make it find brackets, braces, etc on a line that has characters already on it.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    The code needs to look at the characters on a line one at a time.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    I thought using the readLine() method would automatically read the entire line until it found no more words/characters then move to the next line?

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    readLine() method would automatically read the entire line
    Yes, that is what it does.
    A line is some characters followed by an end of line character.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    ok, so would i need to convert each line during the while loop into an array of characters before passing them into the if statements checking for proper types?

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    That is one way. Another could use charAt()
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    how would you implement charAt()? because i don't know exactly where the braces, brackets, etc will be?

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    i don't know exactly where the braces, brackets, etc will be?
    That means start at 0 and go to the end of the line.
    If you don't understand my answer, don't ignore it, ask a question.

  23. #23
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    so what would you attach charAt() too? Would you simple say if(strLine.charAt() = "{") then do this.....?

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Using Stacks Homework Help

    Did you read the String class's API doc to see how to use the charAt() method?
    The code you posted makes it look like you have not read the doc for the method.

    What does the compiler say when you give it the line you posted?
    If you don't understand my answer, don't ignore it, ask a question.

  25. #25
    Member
    Join Date
    Feb 2013
    Location
    Georgia
    Posts
    44
    My Mood
    Fine
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using Stacks Homework Help

    haha, i read it and did some text, using it with a variable that i tried to increment after each readLine call.

    int x = 0;

    after the readLine did x++;

    and then it went into:

    if("{".equals(strLine.charAt(x)))

    I think i'm a bit confused on what is actually being held in strLine after each readLine(), is it holding just one element or the contents of each line?

Page 1 of 2 12 LastLast

Similar Threads

  1. Stacks
    By RoshanDiMatteo in forum What's Wrong With My Code?
    Replies: 3
    Last Post: December 3rd, 2012, 11:22 AM
  2. Stacks
    By RoshanDiMatteo in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 3rd, 2012, 10:21 AM
  3. stacks
    By bd0652 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: September 10th, 2012, 11:48 AM
  4. Help with Stacks
    By animelook in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 17th, 2010, 12:58 AM
  5. help for stacks
    By msa0127a in forum Algorithms & Recursion
    Replies: 0
    Last Post: October 3rd, 2010, 12:11 AM