Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads an input text file consisting of a list of arithmetic

ID: 3554123 • Letter: W

Question

Write a program that reads an input text file consisting of a list of arithmetic expressions, one expression on each line. Each arithmetic expression may consist of three kinds of brackets, namely, ( ), [ ] and { }. There could either be spaces or no space between the brackets and arithmetic operators and variables.

The program should read each line and check if it is balanced with respect to the three symbols. For this, you should use a stack. The program should report whether each line is correct or incorrect. The output for the above example would be (printed on the standard output, not to a file).

**** I already have the Stack Method,I just need the Main Method****

Explanation / Answer

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Stack;
public class BracketMatch {
public static void main(String[] args) {
BracketMatch match = new BracketMatch(); // change file name here File f = new File("input.txt");
BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); String line; while ((line = br.readLine()) != null) { boolean result = checkvalidExpression(line); if(result) System.out.println("Expression :"+line+" is matched"); else System.out.println("Expression :"+line+" is not matched"); } } catch (IOException e) { e.printStackTrace(); } try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public static boolean checkvalidExpression(String expr){
Stack<Character> charStack = new Stack<Character>(); int len = expr.length(); char exprChar = ' ';
for(int indexOfExpr = 0; indexOfExpr<len; indexOfExpr++){ exprChar = expr.charAt(indexOfExpr); if(exprChar == '(' || exprChar == '{' || exprChar == '['){ charStack.push(exprChar); } else if(exprChar == ')' && !charStack.empty()){ if(charStack.peek() == '('){ charStack.pop(); } } else if(exprChar == '}' && !charStack.empty()){ if(charStack.peek() == '{'){ charStack.pop(); } } else if(exprChar == ']' && !charStack.empty()){ if(charStack.peek() == '['){ charStack.pop(); } } else if(exprChar == ')' || exprChar == '}' || exprChar == ']' ){ return false; } } if(!charStack.empty()) return false; return true; } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote