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:
Turn in the zipped project
- Declare a stack (you have to decide on the type of the elements in the stack)
- Set type of error = 0
- For each symbol in the expression string do:
- If it is ( push. (Here you decide what to push does not actually matter)
- If it is )
if stack is empty set type of error = 2, exit the loop
otherwise pop from the stack
- After the end of the loop
If no error,
if stack is not empty, set type of error = 1
- Return type of error
- You dont 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)