Question: Examine the following method – explain what it does; write the pre and post conditions.
For pre and post conditions I have:
- PreCondition: The String cannot be blank.
- PostCondition: A boolean value of true or false is returned whether the stack is empty once the program steps out of the for loop.
For explaining what the code does I have:
The method loops through all the characters of the string p. It takes each individual characters and analyzes. If it’s a left delimiter such as a parenthesis or a bracket, it adds it inside the stack which is referenced by the reference variable s. If it’s a right parenthesis, the method looks at the stack to see if it’s empty or there is no corresponding left parenthesis. If one of those condition is true then it returns false. The same is done if the next character is a right bracket. The default statement which throws an IllegalArgumentException if none of those cases executes.
This pseudocode is designed to determine if a sequence of parentheses is balanced. This design doesn't work. Here I give reasons for why it is an invalid design. Does anybody disagree with my statement? Also what (unbalanced) sequences will the code think is balanced?
- After the white loop executes it will print “balanced” regardless if the sequence is balanced or not.
- Since it will print balanced regardless of the sequence, all unbalanced sequence will be regarded as balanced by the code.
declare a character stack
while ( more input is available)
read a character
if ( the character is a '(' )
push it on the stack
else if ( the character is a ')' and the stack is not empty )
pop a character off the stack
print "unbalanced" and exit
With regards to your explanation of what the code does, I think you have gone into too much detail.
Taking the example from the pseudocode exercise: "determines if a sequence of parentheses is balanced"
That is a great example of saying what the code does, without going into detail.
You've written an almost blow by blow of the logic implemented in the code.
If you give that explanation to a non-technical person, their first question would be "but what does it DO?"
Mike. J. Thompson wrote:For preconditions list the things that will cause the method to throw an exception. I can see one explicit case, and one implicit case.
If the next character is not a delimiter, if it was a letter then none of the cases will execute and it will go to default and throw an exception. So another precondition will be the string has to be parenthesis or brackets or it will throw an IllegalArgumentExpetion?
You get good luck from rubbing the belly of a tiny ad: