Question

Write a program that takes a file as input and checks whether or not the content...

Write a program that takes a file as input and checks whether or not the content of the file is balanced. In the context of this assignment “balanced” means that your program will check to make sure that for each left bracket there is a closing right bracket.

Examples:

            [ ( ) ] { } à balanced.

            [ ( ] ) { } à unbalanced.

Here is the list of brackets/braces that program must support:

  • (: left parentheses (NOT smiley face).
  • ): right parentheses (again NOT sad face)
  • [: left square bracket
  • ]: right square bracket
  • {: left curly bracket
  • }: right curly bracket
  • <: left angle bracket
  • >: right angle bracket

Have to implement this program using the Stack data structure. Feel free to use either ArrayStack or LinkedStack from the textbook or build your own class.

Other requirements:

  • File input/output:
    • program should detect empty files and throw an exception displaying the following message: “This file is empty + fileName”.
    • program should detect invalid file names and throw an exception displaying the following message: “File doesn’t exist + fileName”.
  • After you process the input file you have to display the content of the file as well as a message saying either “balanced” or “unbalanced”.
  • Print the line number where the unbalanced bracket is found.
  • You will need at least the following three classes:
    • Driver: main
    • ArrayStack or LinkedStack: data structure
    • SimpleParser: read the file, check balance, …
    • program should be able to read the file name from the command prompt:
      • Example: java Driver Foo.java

using java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Output:


code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;

public class BalancedParantesisSolution {

   private boolean isInPair(Character character1, Character character2) {

       return (character1.equals('(') && character2.equals(')')) || //
               (character1.equals('{') && character2.equals('}')) || //
               (character1.equals('[') && character2.equals(']')) || //
               (character1.equals('<') && character2.equals('>'));
   }

public static boolean isParenthesisBalanced(char[] exp) {

       Stack<Character> stack = new Stack<>();

       for (int i = 0; i < exp.length; i++) {

           if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[' || exp[i] == '<') {
               stack.push(exp[i]);
           }

           if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']' || exp[i] == '>') {
               if (stack.isEmpty()) {
                   return false;
               } else if (!isInPair(stack.pop(), exp[i])) {
                   return false;
               }
           }

       }

       return stack.isEmpty();
   }

   public static void main(String[] args) {
       if (args.length == 0) {
           System.out.println("Usage : \n java -jar driver.jar fileToBeparsed.txt");
       } else {
           String fileName = args[0];

           File file = new File(fileName);

           try (BufferedReader br = new BufferedReader(new FileReader(file))) {

               if (file.length() == 0) {
                   System.out.println("This file is empty " + fileName);
                   return;
               }
               String currentLine;

               while ((currentLine = br.readLine()) != null) {

                   System.out.println(currentLine + " is " + //
                   (isParenthesisBalanced(currentLine.replaceAll(" ", "").toCharArray()) ? "balanced" : "unbalanced"));
               }

           } catch (FileNotFoundException e) {
               System.out.println("File doesn’t exist " + fileName);
           } catch (IOException e) {
               System.out.println("Error reading file " + fileName);
           }

       }

   }

}

<terminated BalancedParantesisSolution Java Application] [) < is unbalanced [( ) ) { } is unbalanced

<terminated BalancedParantesisSolution Java Application] [) < is unbalanced [( ) ) { } is unbalanced

Add a comment
Know the answer?
Add Answer to:
Write a program that takes a file as input and checks whether or not the content...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ Write a program that prompts for a file name and then reads the file to...

    C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on.

  • FOR JAVA Write a program that takes two command line arguments: an input file and an...

    FOR JAVA Write a program that takes two command line arguments: an input file and an output file. The program should read the input file and replace the last letter of each word with a * character and write the result to the output file. The program should maintain the input file's line separators. The program should catch all possible checked exceptions and display an informative message. Notes: This program can be written in a single main method Remember that...

  • Write a Java program that inputs a list of integer values in the range of −...

    Write a Java program that inputs a list of integer values in the range of − 1 to 100 from the keyboard and computes the sum of the squares of the input values. This program must use exception handling to ensure that the input values are in range and are legal integers, to handle the error of the sum of the squares becoming larger than a standard Integer variable can store, and to detect end-of-file and use it to cause...

  • Use PYTHON Write a program that will take an input file called input.txt which will contain a Jav...

    use PYTHON Write a program that will take an input file called input.txt which will contain a Java program and parse it and output an annotated version. Your program will track the nesting depth of the braces of the input file and will output an annotated version of the file. Your final program will 1. List the nesting depth of curly braces 2. Ignore braces inside quotes or comments Use Python Assume that all quoted strings begin and end on...

  • Write in Java please. The purpose of this program is to read a file, called WaterData.csv....

    Write in Java please. The purpose of this program is to read a file, called WaterData.csv. It will output date and gallons. So it would look something like "2/04/15 40 Gallons". The pseudo code is as follows. prompt the user for a file name open the file if that file cannot be opened display an error message and quit endif create a String variable 'currentDate' and initialize it to the empty string. create a variable gallonsUsed and initialize it to...

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

  • Programming in C. Name this program schwifty.c - This program reads a text file and makes...

    Programming in C. Name this program schwifty.c - This program reads a text file and makes it schwifty, but the user determines the schwiftiness. The user supplies the filename to schwift and a string containing a sequence of the following characters to determine the schwiftiness via command line arguments: L - Left shift each character in a word: hello --> elloh R - Right shift each character in a word: elloh --> hello I - Shift the letters' and digits'...

  • You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an...

    You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an array of instances of the class Book. The class Book is loaded in our Canvas files: Book.java The user will enter a number n (n must be > 0, trap the user until they input a valid value for n), Your program will declare and create an array of size n of instances of the class Book. The user will be asked to enter...

  • For this project you will implement a simple calculator. Your calculator is going to parse infix...

    For this project you will implement a simple calculator. Your calculator is going to parse infix algebraic expressions, create the corresponding postfix expressions and then evaluate the postfix expressions. The operators it recognizes are: +, -, * and /. The operands are integers. Your program will either evaluate individual expressions or read from an input file that contains a sequence of infix expressions (one expression per line). When reading from an input file, the output will consist of two files:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT