I am writing a program to check for delimeters \" { \" , \" } \" , \" ( \" , \"
ID: 3530690 • Letter: I
Question
I am writing a program to check for delimeters " { " , " } " , " ( " , " ) " , " [ " , " ] " , basically the program is to take a text file with some code in it and make sure that for every opening bracer, bracket, or parenthesis that it has a closing point that is in the proper place. For example if you the file contiaing:
[
while(x = 22)
{
r = 4;
}
the code should push " [ " , " ( " and " { " onto the stack and then reread the file and pop everytime it comes to the counterpart in the correct order. The above would give an error because it push's on the open brace but never closes it. Another example:
{
while(x = 23)
[
{
r == 8;
]
}
would throw an error because the last item on the stack should be the first to pop off and match its counterpart, in this case the last on the stack is " { " and the next time through the code would encounter " ] " before " } " which is wrong. My code is below and works properly with exception to finding all the delimeters, i have attached at the bottom of the code the example text I was using.
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(" ");
}
}
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(" Elements in stack:");
System.out.println(st);
System.out.println(" "); //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)
*/
Explanation / Answer
I can give you a better suggestion, instead of reading and going through the file twice, once for push operations and 2nd for pop operations. I advice you to do both at the same time.
I had given the same assignment by my prof. to implement it in C language. whenever we encounter a opening bracket (ex: '{' ) I pushed it onto stack and whenever i encounter a closing bracket (ex: '}' ) i poped last item from the stack and check whether it is its counter opening brace(both should be same type). If any any point it fails, then text-code is wrong. At the end stack should be empty.If all are ok, then text is perfect.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.