Infix to postfix printing out incorrectly sometimes..any ideas?

alright, my program this time is to make an infix to postfix converter.
I have it coded, and it works fine except when I use parenthesis. I'm supposed to test it with these expressions:
a + b
a * b + c
a * ( b + c )
a + b * c - d
( a + b ) * ( c - d )
a - ( b - ( v - ( d - ( e - f ))))
     // initialize two stacks: operator and operand
     private Stack operatorStack = new Stack();
     private Stack operandStack = new Stack();
     // method converts infix expression to postfix notation
     public String toPostfix(String infix)
          StringTokenizer s = new StringTokenizer(infix);
          // divides the input into tokens for input
          String symbol, postfix = "";
          while (s.hasMoreTokens())
          // while there is input to be read
               symbol = s.nextToken();
               // if it's a number, add it to the string
               if (Character.isDigit(symbol.charAt(0)))
                    postfix = postfix + " " + (Integer.parseInt(symbol));
               else if (symbol.equals("("))
               // push "("
                    Character operator = new Character('(');
                    operatorStack.push(operator);
               else if (symbol.equals(")"))
               // push everything back to "("
                    /** ERROR OCCURS HERE !!!! **/
                             while (((Character)operatorStack.peek()).charValue() != '(')
                         postfix = postfix + " " + operatorStack.pop();
                    operatorStack.pop();
               else
               // print operatorStack occurring before it that have greater precedence
                    while (!operatorStack.isEmpty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
                         postfix = postfix + " " + operatorStack.pop();
                    Character operator = new Character(symbol.charAt(0));
                    operatorStack.push(operator);
          while (!operatorStack.isEmpty())
               postfix = postfix + " " + operatorStack.pop();
          return postfix;
// method compares operators to establish precedence
     public int prec(char x)
          if (x == '+' || x == '-')
               return 1;
          if (x == '*' || x == '/' || x == '%')
               return 2;
          return 3;
/** MY STACK **/
import java.util.LinkedList;
public class StackL {
  private LinkedList list = new LinkedList();
  public void push(Object v) {
    list.addFirst(v);
  public Object peek() {
    return list.getFirst();
  public Object pop() {
    return list.removeFirst();
  public boolean isEmpty()
      return (list.size() == 0);
}weird, it erased my question/errors I put in...
When I use any of the expressions with parenthesis (except the 2nd to last one) I get an emptystackexception pointing to the area noted in the code.
When I test the 2nd to last one (the one I would expect it to give me the most trouble) it prints out an answer, but it is incorrect. It prints out this : "Expression in postfix: a ( b - ( c - ( d - ( e - f ) -" which is incorrect, as it hsould have no parenthesis
Edited by: Taco_John on Apr 6, 2008 12:46 PM
Edited by: Taco_John on Apr 6, 2008 12:47 PM
Edited by: Taco_John on Apr 6, 2008 12:49 PM

the algorithm we were told to use is here:
While not stack error and not the end of infix expression
a.) Extract the next input token from the infix expression (can be constant value, variable, arithmetic operator, left or right parenthesis)
b.) If token is
- left parenthesis : push it onto the stack
- right parenthesis : pop and display stack elements until the left parenthesis is popped (don't sisplay right parenthesis). It's an error if stack becomes empty with no matching right parenthesis found.
- Operator : if the stack is empty or token is higher priority than the top element, push it onto the stack. Otherwise, pop and display the top stack element and repeat comparison of token with new top element
Note : left parenthesis in the stack is assumed to have a lower priority than any operator.
- operand : display it
When the end of the infix expression is reached, pop and display remaining stack elements until it is empty.
it works fine on anything without a parenthesis, and it prints an answer (however it is incorrect) for the a - (b-(c-(d-(e-f)))) expression.
still looking for an idea if I can get one
Ok, I just noticed this. If i do a * ( b + c ) I get the error. But if I type " a * ( ( b + c ))" with spaces between the left parenthesis and adding an extra parenthesis as well, and NOT spacing the right parenthesis, I get a result that works just like that 2nd to last was doing. So it's something about the spaces...The answer is incorrect when I use the parenthesis as well. So it's not ignoring white space correctly for some reason and it's printing incorrect answers when I use parenthesis.

Similar Messages

  • My Canon MP620 just stopped printing text: it can print photos etc but when I send a word document (with a picture) it only prints the picture. Any ideas?

    Hi Everyone:
    I have a  Canon MP620 printer connected directly into my Airport base station. So far it has worked perfectly - I can print any type of document over the network from my MacBook Pro.
    Yesterday something weird happened. I have a resumé (as a word document) I was always printing but this time all that was printed was a photo and no text. I did a print preview and it looked fine. I converted to PDF and nothing was printed. I then created a brand new word document and again nothing was printed. I have no problem with images but for some strange reason no text  can be printed. All that happens is that the paper goes through and comes out blank.
    Any ideas?????
    Thanks a lot in advace!

    Hi,
    Tried all the cleaning programmes and it still will not print...I am lost.

  • My mac keeps freezing when i try and print anything from preview. any ideas as to what the issue is or how to fix it?

    my mac keeps freezing when i try and print anything from preview. any ideas as to what the issue is or how to fix it?

    Please read this whole message before doing anything.
    This procedure is a test, not a solution. Don’t be disappointed when you find that nothing has changed after you complete it.
    Step 1
    The purpose of this step is to determine whether the problem is localized to your user account.
    Enable guest logins and log in as Guest. For instructions, launch the System Preferences application, select Help from the menu bar, and enter “Set up a guest account” (without the quotes) in the search box.
    While logged in as Guest, you won’t have access to any of your personal files or settings. Applications will behave as if you were running them for the first time. Don’t be alarmed by this; it’s normal. If you need any passwords or other personal data in order to complete the test, memorize, print, or write them down before you begin.
    Test while logged in as Guest. Same problem(s)?
    After testing, log out of the guest account and, in your own account, disable it if you wish. Any files you created in the guest account will be deleted automatically when you log out of it.
    Note: If you’ve activated “Find My Mac” or FileVault in Mac OS X 10.7 or later, then you can’t enable the Guest account. Create a new account in which to test, and delete it, including its home folder, after testing.
    Step 2
    The purpose of this step is to determine whether the problem is caused by third-party system modifications that load automatically at startup or login.
    Disconnect all wired peripherals except those needed for the test, and remove all aftermarket expansion cards. Boot in safe mode and log in to the account with the problem. The instructions provided by Apple are as follows:
    Be sure your Mac is shut down.
    Press the power button.
    Immediately after you hear the startup tone, hold the Shift key. The Shift key should be held as soon as possible after the startup tone, but not before the tone.
    Release the Shift key when you see the gray Apple icon and the progress indicator (looks like a spinning gear).
    Safe mode is much slower to boot and run than normal, and some things won’t work at all, including wireless networking on certain Macs.
    The login screen appears even if you usually log in automatically. You must know your login password in order to log in. If you’ve forgotten the password, you will need to reset it before you begin.
    Note: If FileVault is enabled under Mac OS X 10.7 or later, you can’t boot in safe mode.
    Test while in safe mode. Same problem(s)?
    After testing, reboot as usual (i.e., not in safe mode) and verify that you still have the problem. Post the results of steps 1 and 2.

  • Just started getting "The Apple Id you entered couldn't be found or the password was incorrect".  Any ideas why?

    Just started getting "The Apple Id you entered couldn't be found or the password was incorrect".  Any ideas why?  iTunes is running, the Apple Id and password are being entered correctly.

    Hi skn728,
    If you can verify that your Apple ID and password are correct by logging in at AppleID.apple.com and are certain that all your apps were purchased under that ID, you may want to try manually logging out of your Apple ID on your iPhone, then logging back in. You may find the following article helpful:
    iOS: Sign in with a different Apple ID in the iTunes Store, App Store, and iBooks Store
    http://support.apple.com/kb/ht1311
    Regards,
    - Brenden

  • I have an iphone with the app GOOD to read e-mails.  I sync to my other PC having first updated itunes.  During sync it reported that it had removed GOOD, with out asking.  Any ideas?

    I have an iphone with the app GOOD to read e-mails.  I sync to my other PC having first updated itunes.  During sync it reported that it had removed GOOD, with out asking.  Any ideas?

    With the iPhone, you can sync all iTunes content with only one computer.  Trying to sync iTunes content with a second computer will result in iTunes erasing the content from the first computer.

  • HT4623 I used to be able to print from my iPad, but it has stopped, however I can still print from my iPod, any ideas?

    I used to be able to print from my iPad, but it has stopped, however I can still print from my iPod, any ideas?

    Re-booting Pad, router and printer seems to have solved the problem!

  • Canon MX920 not responding when hooked up over wifi as WPS printer on Airport Extreme, any ideas?

    Canon MX920 not responding when hooked up over wifi as WPS printer on Airport Extreme, any ideas?

    Ping the IP address of the printer.
    If you are doing this from windows, have you installed the airport utility for windows?

  • HT201320 Hi, I cannot access my gmail from my iphone. The password is correct and I can access fine from my computer but the iphone keeps telling me the password is incorrect. Any ideas?

    Hi, I cannot access my gmail from my iphone. The password is correct and I can access fine from my computer but the iphone keeps telling me the password is incorrect. Any ideas?

    I believe Gmail has an option for Two-Step verification that may require a different password for mobile devices than for your computer.
    https://support.google.com/mail/answer/2703311?hl=en

  • HT4557 i just had a new phone today,,i have setup my phone and charged it 100% but the battery is running out very fast.any idea why it is happening ? would really appreciate your help thanks

    i just had a new phone today,,i have setup my phone and charged it 100% but the battery is running out very fast.any idea why it is happening ? would really appreciate your help thanks

    Here are the iPhone battery conservation tips.
    iPhone
    Watch some of the things you may have set up as the article suggests.  Check email fetch frequency, push notifications, location services, etc.

  • Colors print out incorrectly

    When I print out an Illustrator file the color on the paper appears different then on Illustrator. Sometimes it might even be the same exact color, but it would print in two different shades of that color. How can I resolve?
    Any help would be greatly appreciated, thanks!

    Calibrate and profile your monitor, turn off color management in your printer driver, let Photoshop manage color and assign the correct ICC profile for your ink/paper combination.
    Let us know if that doesn't work.

  • Windows vista I want to add a device (printer) to color mgmt any ideas?

    I have a Pavilion Slimline w/windows Vista.  I cannot figure out how to add a device (a printer) to the color management portion of Windows Vista or hp setup.  I really don't know which.  Any ideas?? Thanks for your time.
    Eff

    Hi @Effie12,
    Welcome to the HP Forums!
     I understand that you are wanting to add a device (printer) to Windows Vista, and I am happy to help!
    I believe this is the guide you want to take a look through, Add or remove a printer.
    Otherwise, you may need to download the drivers, you can do that at this website. Drivers & Downloads. If you don't know your printer's Product/Model Number, follow instructions in this link. Finding Your HP Product Model Number.
    Hope this helps!
    RnRMusicMan
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos Thumbs Up" to say “Thanks” for helping!

  • In pages, when I make a table, the lines print very faintly.  Any ideas?

    Hello:  when I make a table in Pages, the table will not print well; the grid lines are very faint.
    I get the same result in Numbers. 
    Any ideas?

    Hello.
    You can choose the size of your border in Pages or Numbers.
    To do that, you have to select your table.
    After that, click on inspector.
    You must have the cell borders option, set here the border width.
    That's all !

  • I just got my Droid Turbo. Deleted lots of emails yesterday and now not receiving any. When I try to refresh, I get an internal error, but can't figure out why. Any ideas?

    I just got the Droid Turbo.  I deleted several emails yesterday and now today, I am not receiving any.  When I try to refresh, I get an internal error. I have tried turning the phone off and checked my settings as well, but still getting nothing. Any ideas??

    I figured it out. Deleted and re-added the account.

  • Timeline Grayed-out/blank. Any ideas?

    So I was resizing a clip of my *almost* finished project, and suddenly as I dragged the clip to make it longer, the entire timeline blanked out.
    At first I thought I was inside a compound clip until I tried opening other projects, or anything for that matter. The timeline just stays grayed out or blank. I can't zoom in or anything, it almost seems like the entire timeline just corrupted in Final Cut.
    I deleted my prefs and layout, nothing changed, then I reinstalled the program and it seemed cured as I could open other projects. But when I tried opening the orginal project (the one the program crashed on) suddenly the timeline blanks out again, and then it won't open any other projects again.
    It's like my project is screwing up the entire Final Cut program...
    I've already pretty much resigned myself to the idea that I'm going to have to start over, but I was wondering if anyone else had found a solution to this problem. From what I understand, this problem isn't uncommon, I just haven't been able to find a solution yet. Any ideas?

    OKAY - I just read some other discussions on this (sorry - didn't see it until after I posted) and NOW I understand my problem - I got it fixed - thanks!

  • HT1296 My phone is picking up all my photos from my computer when I sync it and then running out of space - any ideas how to stop that?. Want to download not upload!!!

    My phone is uploading photos from my computer when I sync it - any ideas how I can stop this and remove what it's uploaded already?? Edit functions on phone won't delete the uploaded albums :-/

    Connect the iPhone to your PC/Mac with iTunes open.
    On iTunes do this:
    - go to summary (left hand side)
    - select the option photos to the right
    Here you need to decide how you would like to set how your iPhone syncs photos from your PC/Mac. Its is up to you wether you only want to sync selected or all photos. Once you have made the changes select "Apply" to the bottom right.
    Hope this helps

Maybe you are looking for