سؤال

For my homework assignment, we are supposed to use stacks to make a calculator using infix and postfix in java. While I am reading in the equations from the file, there are lots of parentheses. I am supposed to make sure they match up and have an error message to display if they are empty, or if there are parenthesis that match up. I'm not sure how to go about checking for matching parenthesis. Any code, or help with the logic behind it would help. I have wasted a large amount of time trying to figure out a pretty small part of this homework.

The input file contains: (((A + B) - (C - D)) / (E - F)) (((A))) (A) ((A (B D) D)) () (( )) (((A + B))) ((A * B)) (A / B) A * B A / B + C A ^ (B - C) (((C ^ E))) D ( A - B * C) A- B / C ( A / B * C) ( A - C ^ C) ( A * C ^ C) ( D / C ^ C) A - C ^ C A - B * C +D / E A*B - C ^ C ^ D A B - C ^ C ^ D (( A - B * C) ^ D ^ E) ^ ( F / G * H + I ) (A - B) * (( C * D ) + E) ((( )(( ) )(((( )))) ((( )(( ) (((( )))) A * ( B / C) + D( A - B) A * ( B / C) + D ^ ( A - B) A * ( B / C) + D ^ A - B

هل كانت مفيدة؟

المحلول

Think about it logically. How do you know if they match up? If you have a closing brace after an opening brace.

Here's a general algorithm:

  • If encounter an opening brace "(", add to stack
  • If encounter closing brace ")", pop one from the stack
  • If you encounter a closing brace, be careful to check the stack size. If nothing is on the stack then that is also an error.

Once text has been parsed, your stack should be empty if there was a matching amount of braces and no errors encountered.

نصائح أخرى

use the stack - push onto stack when you see any open parentheses, and pop from stack when you see the closing ones. If you try to pop but the stack is empty, then it doesn't match. If you have no more input but still have things in your stack, that also means that it doesn't match

Try looking into stack data structure. It is a first-in-last-out type of structure, where you can store multiple elements in a specific order and you always retrieve them in reverse order.

You can then scan the code and everytime you find an opening parenthesis, you push it onto the stack and when you find a closing one, you pop the opening parenthesis out. When you reach the end of the code, the stack should be empty and you should never encounter a situation, when you are popping on an empty stack, then you know the parenthesis are correct.

It is simple. Read from the input file.
If you've read '(' add it to the stack.
If you've read ')' peek what's on the top of the stack.

  • If the stack is empty, raise an error.
  • If it is '(' then pop from the stack, ignore the char ')' you've just read, and move on reading.
  • If it is not '(' then raise an error.
  • If you've read the whole input and your stack is not empty, then raise an error.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top