stacks - verify well-formed equations, InFix to PostFix

Hi...
I'm a new user here. I've stumbled across this place on a couple occasions in the past, and it worked out to my advantage when I needed a little help with some coding assignments.
My Data Structures class is working on stacks right now, and that is our current assignment.

This assignment is 3 parts, 1 of which is optional for extra credit.
The 2 parts I am working on, before hopefully also doing the third for extra points, are as follows:

1) verify whether or not equations are balanced, according to parentheses, brackets, and curly braces.

2) InFix to PostFix conversions.
example: (a+b)*c => ab+c*

All of the parts need to evaluate from a .txt file that is read in.
Here is what I have thrown together so far:

This code I've provided will read in the .txt file and analyze each line at a character level, which I'm sure I need to do for this assignment. I've also included the structure for my stack class.

I've been staring at it for a while now, and I'm a little stumped with where to go from here. Perhaps I need to go back and reread some of the material on stacks and stack operations in order to get a clearer picture of what exactly I need to do.

Any tips or pointers of which direction to go from here would be greatly appreciated! :cool:

I can help you get started. The easiest way to verify if its a valid equation is to try to convert it and throw an exception if you run into a problem with it. If you haven't learned about exceptions yet, then one way to go is to traverse through the equation and push each left paren onto a stack, and then remove one each time you find a right paren. If there are parens left in the stack when you're done, or if the stack is empty and you find a right paren, then it isn't balanced.

As far as converting goes, here is a good algorithm for converting postfix to infix. You hopefully shouldn't have too much trouble converting it to java code. You'll have to add a little more to process parenthetical portions.

I can help you get started. The easiest way to verify if its a valid equation is to try to convert it and throw an exception if you run into a problem with it. If you haven't learned about exceptions yet, then one way to go is to traverse through the equation and push each left paren onto a stack, and then remove one each time you find a right paren. If there are parens left in the stack when you're done, or if the stack is empty and you find a right paren, then it isn't balanced.

As far as converting goes, here is a good algorithm for converting postfix to infix. You hopefully shouldn't have too much trouble converting it to java code. You'll have to add a little more to process parenthetical portions.

Good luck!

Thanks for that link. I will look it over and try to put some of that info to use.
About the equation verification...what would be the most logical way to test whether a right paren/bracket/brace comes up (in order to pop the top object off the stack)? To test each character of the line with if statements for each "right" paren/bracket/brace? While analyzing each character of the line, would this, in theory, require six if statements - one for each possible case of opener/closer of parens/brackets/braces?

What if there are say three left parentheses on the stack, but then a right bracket appears? How would the program know that the bracket doesn't match, since there are only parentheses on the stack? Should each character be tested every time to see if it's a "closer" and if it matches with whatever "opener" is on top of the stack?

inside a for-loop to step through it character by character. You would need six if statements inside said for-loop for, 2 for each type of bracket. However, if you aren't restricted from altering the original equation, you could use that

{ 2 * 3 + ( 4 / [ 8 - 6 ] ) } == ( 2 * 3 + ( 4 / ( 8 - 6 ) ) )

You could run through the equation once and convert curly and square brackets to their paren counterparts. If doing this doesn't violate the rules in the assignment, it'll definitely make your life easier. This way you'd only need two if statements when verifying if its a balanced equation, and you could do it all with one stack.

Alternatively, if you can't change the brace types, you'll probably need 3 stacks; 1 for each type of bracket.

Keep in mind, verifying if it's a valid equation also requires you to make sure every operator you come across is a valid operator too.

Thanks a lot for your helpful insight. I will put some of it to use!
If you're bored, I posted another thread concerning my previous class assignment. (it's already been turned in, but I was having one problem with it and I'm stumped as to what is causing the problem)

What if there are say three left parentheses on the stack, but then a right bracket appears? How would the program know that the bracket doesn't match, since there are only parentheses on the stack?

edit: If a closed bracket is encountered when a '(' is on the top of the stack, then you know already that you have an error. So when you see a '}', you should attempt to pop a '{' off of the top of the stack. If the element on top of the stack is not a '{', then you have an error. (If this doesn't make sense, read the rest of my post first, then re-read this).

Should each character be tested every time to see if it's a "closer" and if it matches with whatever "opener" is on top of the stack?

When you see an open bracket, you should push an open bracket onto the stack. When you see a closed bracket, you should pop an open bracket from the stack. If you see a closed bracket, and there are no open brackets left on the stack, then you have just encountered an error. After analyzing an entire set of brackets, your stack should be empty, indicating that the same number of open and closed brackets were seen, in an acceptable order. (For example, {{}}}{ has three open brackets and three closed brackets, but it is not in an acceptable order. If your program encountered {{}}}{ it should do the following:

Stack after seeing { = {
Stack after seeing {{ = {{
Stack after seeing {{} = {
Stack after seeing {{}} = (empty)
Stack after seeing {{}}} = error, because you just saw a closed bracket, but it is impossible to pop an open bracket from the stack.

In a nutshell, your job is to push "open" (brackets, parens, curly braces) onto the stack when you see an "open" (bracket, paren, curly brace), and then to pop the top of the stack when you see a closed type (so if you see a closed brace, you pop the top element of the stack). Then you have to check the element that you just popped off of the stack to make sure it is an open brace.

Thanks for the tips, BestJewSinceJC. I've added a little more code and looked at it for a little while, and it's all become substantially clearer. You definitely worded it in an easy to understand sort of way.
It's basically little concepts that I've gathered over the last little while of sitting and thinking about it, but it definitely helps to read another person's explanation of the logic in their own words.

Would it make more sense to do what you say, or to have 3 separate stacks, one for each parentheses, brackets, and braces?

I have a feeling that one consolidated stack would make the most sense, but would require that extra bit of code to determine if an inappropriate "closer" comes up that doesn't match the last "opener" on top of the stack... but with the 3 dedicated stacks, the program could just check whichever stack it needs to...right?

This is the small bit I've added, but it's throwing me an ArrayIndexOutOfBoundsException.

You can't use three separate stacks because consider the following input:

{(})

That input isn't valid, and should result in an error. But if you use separate stacks for each symbol, it will appear legitimate and it won't cause an error. And I'll take a look at your code momentarily.

edit: It looks like you're using separate stacks, which I do not think is correct for the reason I listed above. The order in which the braces/brackets/parens are seen is very important, and using different stacks does not keep track of the order they were seen in. You should implement one stack where you use a few comparisons to make sure things are valid.

You'd have the following comparisons:
1) the case where you just saw a }. You'd have code similar to this pseudocode:

typeOfBrace = readInNextBrace();
if (typeOfBrace == '}' or typeOfBrace == ')' or typeOfBrace == ']') //You have to make sure its a closed type before you pop.
topElement = stack.pop();
if (typeOfBrace == '}'){
if (topElement == '{') // there's no error!
} else //there's an error, do something!

2) the case where you just saw a ]. Pseudocode:

typeOfBrace = readInNextBrace();
if (typeOfBrace == '}' or typeOfBrace == ')' or typeOfBrace == ']') //You have to make sure its a closed type before you pop.
topElement = stack.pop();
if (typeOfBrace == ']'){
if (topElement == '[') // there's no error!
} else //there's an error, do something!

3) There is also the case where you just saw a ), but since the code is so similar to what is above, I won't repost it again. Oh, and obviously, you only want to do the first part of the code that I posted once, not twice. (The part up to and including stack.pop() should only be done one time, then you should have a few if statements afterwards to check the types).

You can't use three separate stacks because consider the following input:

{(})

That input isn't valid, and should result in an error. But if you use separate stacks for each symbol, it will appear legitimate and it won't cause an error. And I'll take a look at your code momentarily.

Ahhh yes, I see what you're saying.
Ultimately, I'd like to end up with just the one stack to handle everything. The assignment only deals with parentheses actually, so I'm doing a little extra involving the brackets and braces.

I updated my last post, you should take a look. And at this point, I'd recommend that you first develop the code for the parentheses then. After you get that working, then add in logic for the brackets and curly braces. It would be pointless to help you complete the separate stacks solution, since the algorithm itself is flawed.

I updated my last post, you should take a look. And at this point, I'd recommend that you first develop the code for the parentheses then. After you get that working, then add in logic for the brackets and curly braces. It would be pointless to help you complete the separate stacks solution, since the algorithm itself is flawed.

Cool, man. Thanks a bunch for the help.
I'm reworking it now. In little chunks, it's all making more and more sense. ;)

Just when I think I have it to where it should work, it won't. :(
Maybe I need a break...

I feel like I'm grasping the basic concept and logic of this assignment, but I'm apparently making an error somewhere, and I can't figure it out.

When I run the following code, I get the "NOT VALID! - (closer with no opener)" error print statement I inserted after every line of equation, whether it is indeed valid or not.

Does my attempted logic and way of tackling this make sense?

edit - On a side note, in regards to the other part of the assignment (Infix to Postfix), what is the easiest way to determine if a character is an operator or operand? Would I need to check each individual character of the equation against each possible operator? (+, -, *, /, etc.) or is there a much simpler way? Can't I somehow analyze each character's ASCII value or something to determine what it is? Anyone have any tips on that?

Because you want to check "if the stack is empty and any one of }, ], or ) is seen, then . . ." but look at your if statement more closely: It will be executed any time a ']' or a '}' is seen, or whenever both the stack is empty and a ')' is seen.

And haha, your error is ironic if that is it, considering the project assignment is about grouping of operators, which was the cause of your error. (But no offense, I've made similar mistakes before)

I fixed that syntax, and understand why it was wrong, but I'm still running into the same problem.
I inserted a showStack() method after every equation is read, but it's showing each stack as being empty. (which should happen if the equation is valid, but it's happening for even the invalid ones)

I'm still convinced (although that doesn't mean much) that my logic in the above code section is correct, so the problem is obviously elsewhere...perhaps in the stack class itself.

Whether or not the stack is empty for an invalid equation depends on your implementation. However, if in your implementation you "pop" an element off of the stack and then compare it to the next '}' or']' or ')', your stack would be empty even if there was an invalid condition.

(Ex: {) ):

Stack after seeing { = {
See ')' and pop top of stack. Top of stack, '{', is not the correct element for ')'. Therefore your stack is empty because you just popped the only element on it, but you have an error condition.

I'm not saying you don't have an error in your stack class, but you can easily come up with an error when your stack is empty if you are popping the elements off the stack before comparing them. If you post all of your classes again (w/ whatever your most up to date code is) I'll look at them later and help you figure out what's wrong.

I think it's working...
It kept giving me an error pointing to the pop() method and where I tried to compare the incoming ), ], or } to the item on top of the stack... so I added a peek() method, and it seems to have fixed whatever the problem was.
I also modified the logic in the section that analyzes each character of the equation.

Cool, glad you got it to work. If there's anything you still have trouble with let me know and I'll help you out later today. I'm going to do a really fun Iphone program so I'll probably be off until then though.

Cool, glad you got it to work. If there's anything you still have trouble with let me know and I'll help you out later today. I'm going to do a really fun Iphone program so I'll probably be off until then though.

Oh, and mark as solved if you don't have any more ?s

Thanks a lot, sir! Your help has been much appreciated. I'm thankful for this place and its good citizens such as yourself.

Working on iPhone stuff, eh? That's awesome. I just got a few good books on iPhone development and Obective-C programming.
Ever since I got my iPhone (shortly after the 3G came out), I've been fantasizing over the idea of making some stuff for it. I downloaded the SDK a little while back and have been lightly toying with it, but now that I have some decent material to teach me, I'm about to start putting some serious hours toward it. That damn iPhone has incredible potential.
I'd love to check out what you come up with.

I did have one more question that I posted earlier, but maybe you didn't notice it. It's about the other (Infix to Postfix) part of this assignment. Here it is:

I checked out a link that another poster provided in post #2 of this thread. It is helpful, but leaves me with one question...
What is the easiest way to determine if a character is an operator or operand? Would I need to check each individual character of the equation against each possible operator? (+, -, *, /, etc.) or is there a much simpler way? Can't I somehow analyze each character's ASCII value or something to determine what it is? Anyone have any tips on that?

Would I need to check each individual character of the equation against each possible operator? (+, -, *, /, etc.) or is there a much simpler way?

Yes, you'd need to compare against each operator. Java uses Unicode, not ASCII, but even if you used the Unicode values, you'd be doing the same thing as comparing against each operator (unless the operators are right next to each other in the Unicode table, in which case, you could say something like "if (charImComparing >=120 && charImComparing <= 125)".

Yes, you'd need to compare against each operator. Java uses Unicode, not ASCII, but even if you used the Unicode values, you'd be doing the same thing as comparing against each operator (unless the operators are right next to each other in the Unicode table, in which case, you could say something like "if (charImComparing >=120 && charImComparing <= 125)".

Yeah, Unicode...that's what I meant. ;)
I was actually hoping that I could do that, what you mentioned...if the operators are next to each other, of course.
Thanks again for your time and help. :)

I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...

Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...