CmSc 155 Fundamentals of Computing II


Homework 05: Check parentheses, due 02/24

Write a program that takes as input an arithmetic expression (read as String) and calls a method int checkPar(String expression) that checks for matching parentheses. The main method has to report the findings depending on the returned value.

The parameter of the method is the entered expression (you can also initialize a String variable in your main method)

The returned value is a number that represents the error:
0 – no errors
1 – Opening parenthesis found without matching closing parenthesis
2 – Closing parenthesis found without matching opening parenthesis

The method will use the Stack class. The Stack class is provided in the package Stacks. Download and unzip: Stacks.zip. The package contains the linked implementation only. Your program needs to have import Stacks.*; statement.

The algorithm is as follows:
  1. Declare a stack (you have to decide on the type of the elements in the stack)
  2. Set type of error = 0
  3. For each symbol in the expression string do:
    1. If it is ‘(‘ push. (Here you decide what to push – does not actually matter)
    2. If it is ‘)’
      if stack is empty set type of error = 2, exit the loop
      otherwise pop from the stack
  4. After the end of the loop
    If no error,
    if stack is not empty, set type of error = 1
  5. Return type of error
Turn in the zipped project

Notes:

  • You don’t need actually to push ‘(‘ in the stack. It does not matter what is pushed.
  • How to exit the loop in emergency – use the break statement, or modify the condition in the header of the loop, so that it runs while the type of error is 0 (i.e. no error has been found)

Back to CMSC 155 home page