How to convert from infix to postfix without using any methods

Viewed 154

We are supposed to write a program using the stack class that converts a string from infix to postfix using JOptionPane as the input method. We are supposed to do it all in one big for loop and one big tester file with no methods, I am not sure why. I am incredibly confused on how to do it but this is what I have so far. It crashes everytime I put something in.

import javax.swing.*;
import java.util.Stack;

public class InfixToPostfix
{
    public static void main(String[] args)
    {
        JFrame f;
        f = new JFrame();

        String eq = JOptionPane.showInputDialog("Enter Equation");
        StringBuilder postfix = new StringBuilder(new String(""));

        Stack<Character> stack = new Stack<>();

        int addSub = 0;
        int multDiv = 0;

        for(int i=0; i<eq.length(); i++)
        {
            char c = eq.charAt(i);

            if(Character.isLetterOrDigit(c))
                postfix.append(c);
            else if(c=='(')
                stack.push(c);
            else if(c == ')')
            {
                while (!stack.isEmpty() && stack.peek() != '(')
                    postfix.append(stack.pop());

                    stack.pop();
            }
            else
            {
                switch (c)
                {
                    case '+':
                    case '-':
                        addSub = 1;

                    case '*':
                    case '/':
                        multDiv = 2;
                }
                while(!stack.isEmpty() && (addSub > multDiv || multDiv > addSub))
                    postfix.append(stack.pop());
                stack.push(c);


            }
            while(!stack.isEmpty())
                postfix.append(stack.pop());
        }
        JOptionPane.showMessageDialog(f, postfix.toString());

    }
}
0 Answers
Related