Program 1 Java One of the most useful real world implementations of Stacks is wi
ID: 3836265 • Letter: P
Question
Program 1 Java
One of the most useful real world implementations of Stacks is with language compilers. We are going to implement a very simple version of a compiler using recursion and the Stack class. As we know, the Stack class has a push and pop. Stack is a built-in java.util class library. You can create an instance like this: static Stack myStack = new Stack(); Then, you can access its methods just as like any other class. In this program, you are going to read in any XML file and check to see if it is valid based on its < and /> brackets. If an open angle bracket "< " is found, you should push it onto the stack, and when you find a closed angle bracket />, you are to pop off the stack. At the end of the program, you should print out whether the file is valid (i.e. the stack is empty) or if invalid (the stack is not empty). You are to read the file in recursively and for each line in the file you are to look recursively through the line and push and pop as necessary.
Specifics:
1. You should use the built in Stack class with its push and pop methods
2. You are to read recursively in a java file.
3. You are to read recursively in each line and push if a < open angle bracket is found and pop if a /> closed angle bracket is found.
4. You should have an appropriate exception handler for the pop.
5. After the recursive calls, you should display whether the file is valid or not.
Sample XML
<note>
<to>
Tove
</to>
<from>
Jani
</from>
<heading>
Reminder
</heading>
<body>
Don't forget me this weekend!
</body>
</note>
Explanation / Answer
import java.util.*;
import java.io.*
void processLine(BufferedReader br, Stack st){
String line;
if (br.readLine() == NULL)
return;
else {
if (line.contains("<")
st.push(1);
if (line.contains("/>")
st.pop();
processLine(br, st);
}
}
public class CheckXML {
public static void main(String args[]) {
Stack st = new Stack();
try {
String line;
BufferedReader br = new BufferedReader(new FileReader(FILENAME));
processLine(br, st);
if (st.empty())
System.out.println("Valid file");
else
System.out.println("Invalid file");
} finally {
if (br != null) {
br.close();
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.