Write a program to input a textfile, and, using a stack, process the entire file
ID: 3640734 • Letter: W
Question
Write a program to input a textfile, and, using a stack, process the entire file, looking for parentheses and curly braces, then to output whether the parentheses and curly braces are properly nested. Any characters other than parentheses and curly braces should be ignored. You can use TextFileReader.java, documented as in these JavaDoc pages, to input a text file from the same folder as the program file. You can use the Stack<E> class from java.util.Note that a good text file to try your program out on is a .java file. Also note that .java files with parentheses or curly braces in comments or quotes may actually not be properly nested even if they compile.
To insure proper Text input, be sure to add a blank line at the end of the input file.
The code must be completed how i asked to get full points. The code must include a comment for each method describing the method, a comment for each parameter describing what the parameter represents, and a comment for each variable declaration (including instance variables) describing what the variable represents.
Explanation / Answer
Used regular java Scanner as I don't know anything about your class TextFileReader. public static void main(String[] args) throws FileNotFoundException { //read file using scanner Scanner sc = new Scanner(new FileReader("input.file")); //stack to hold incoming characters Stack stack = new Stack(); //whether we are successful so far boolean success = true; //while we have incoming chars and successful while(sc.hasNext() && success){ //read next char char c = (char) sc.nextByte(); //if open bracket, push it on the stack if(c == '{'){ stack.push(c); } //try to pop it and match it else{ try{ char top = stack.pop(); if(top != '{') success = false; } catch(Exception e){ success = false; } } } //we have been successful in mathcingm, as well as no other open brackets are there on stack if(success && stack.isEmpty()) System.out.println("Correct parenthesis!!!"); else System.out.println("Incorrect parenthesis!!!"); }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.