The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Jul 2017 |
| Last Sign in: | 304 Weeks Ago, 3 Days Ago |
| Questions Answered: | 15833 |
| Tutorials Posted: | 15827 |
MBA,PHD, Juris Doctor
Strayer,Devery,Harvard University
Mar-1995 - Mar-2002
Manager Planning
WalMart
Mar-2001 - Feb-2009
I am having issue with spaces. Program crashes whenever a space is not implemented. Ex if I put 4*4 and not 4 * 4, the program crash. I also cannot get the program to calculate the numbers correctly whenever it involves ( ) such as ( 2 * 2 ) 2. The program crashesÂ
InFix.java
Â
import java.util.EmptyStackException;
Â
import java.util.Stack;
Â
Â
public class InFix
Â
{
Â
    Stack<String> operandsStk;
Â
    Stack<Character> operatorsStk;
Â
    InFix()
Â
    {
Â
Â
Â
         operandsStk=new Stack<String>();
Â
         operatorsStk=new Stack<Character>();
Â
    }
Â
Â
Â
    public int evaluate(String exp) throws ArithmeticException
Â
    {
Â
         boolean fail=false;
Â
         try
Â
         {
Â
             //Tokenize the string containing the expression while there are more tokens
Â
         String tokens[]=exp.split(" ");
Â
         for(int i=0;i<tokens.length;i++)
Â
         {
Â
             //if it is an operand push it onto the operand stack
Â
             if(!tokens[i].equals("+")&& !tokens[i].equals("*")&&!tokens[i].equals("-")
Â
&&!tokens[i].equals("/") && !tokens[i].equals("(")&&!tokens[i].equals(")"))
Â
             {
Â
                  operandsStk.push(tokens[i]);
Â
             }
Â
             //else if it is a left parenthesis
Â
             else if(tokens[i].equals("("))
Â
             {
Â
                  //push it onto the operator stack
Â
                  operatorsStk.push((Character)tokens[i].charAt(0));
Â
             }
Â
             //else if is a right parenthesis
Â
             else if(tokens[i].equals(")"))
Â
             {
Â
                  //while top of the operator stack not a left parenthesis Â
Â
                  while(operatorsStk.peek()!='(')
Â
                  {
Â
                       // pop two operands and an operator
Â
                       int x=Integer.parseInt(operandsStk.pop());
Â
                       int y=Integer.parseInt(operandsStk.pop());
Â
                       char opr=operatorsStk.pop();
Â
                       //   perform the calculation Â
Â
                       int result=0;
Â
                       if (opr=='+')
Â
                       {
Â
                            result= y+x;
Â
                            //push the result onto the operand stack  Â
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                       else if(opr=='-')
Â
                       {
Â
                            result= y-x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                       else if(opr=='*')
Â
                       {
Â
                            result= y*x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                       else if(opr=='/')
Â
                       { Â
Â
                            result=y/x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
Â
Â
                  }
Â
Â
Â
             }
Â
             //else if it is an operator
Â
             else if(tokens[i].equals("+")||tokens[i].equals("-")
Â
                       ||tokens[i].equals("*")||tokens[i].equals("/"))
Â
             {
Â
                  //while the operator stack is not empty and the operator at the top of the stack has higher
Â
                  //or the same precedence than the current operator
Â
                  while(!operatorsStk.empty()&&hasHigherPrecedence(operatorsStk.peek(),tokens[i].charAt(0)))
Â
                  {
Â
                       //pop two operands
Â
                       int x=Integer.parseInt(operandsStk.pop());
Â
                       int y=Integer.parseInt(operandsStk.pop());
Â
                       char opr=operatorsStk.pop();
Â
                       //perform the calculation Â
Â
                       int result=0;
Â
                       if (opr=='+')
Â
                       {
Â
                            result= y+x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                       else if(opr=='-')
Â
                       {
Â
                            result= y-x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                       else if(opr=='*')
Â
                       {
Â
                            result= y*x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                       else if(opr=='/')
Â
                       { Â
Â
                            result=y/x;
Â
                            //push the result onto the operand stack
Â
                            operandsStk.push(result+"");
Â
                       }
Â
                  }
Â
Â
                  // Push the current operator on the operators stack
                  operatorsStk.push(tokens[i].charAt(0));
Â
             }
Â
         }
Â
         //while the operator stack is not empty
Â
         while(!operatorsStk.empty())
Â
         {
Â
             // pop two operands and an operator
Â
             int x=Integer.parseInt(operandsStk.pop());
Â
             int y=Integer.parseInt(operandsStk.pop());
Â
             char opr=operatorsStk.pop();
Â
             //perform the calculation
Â
             int result=0;
Â
             if (opr=='+')
Â
             {
Â
                  result= y+x;
Â
                  // push the result onto the operand stack
Â
                  operandsStk.push(result+"");
Â
             }
Â
             else if(opr=='-')
Â
             {
Â
                  result= y-x;
Â
                  // push the result onto the operand stack
Â
                  operandsStk.push(result+"");
Â
             }
Â
             else if(opr=='*')
Â
             {
Â
                  result= y*x;
Â
                  // push the result onto the operand stack
Â
                  operandsStk.push(result+"");
Â
             }
Â
             else if(opr=='/')
Â
             { Â
Â
                  result=y/x;
Â
                  // push the result onto the operand stack
Â
                  operandsStk.push(result+"");
Â
             }
Â
         }
Â
         }
Â
         catch(EmptyStackException e)
Â
         {      Â
Â
            fail=true;
Â
         }
Â
         if(fail==false)
Â
             //the final result is at the top of the operand stack
Â
             return Integer.parseInt(operandsStk.pop());
Â
         else
Â
             return -1;
Â
    }
Â
    //returns true, if the top has high precedence than current
Â
    boolean hasHigherPrecedence(char top, char current)
Â
    {
Â
         int topPre=-1;
Â
         int curPre=-1;
Â
         if(top == '+' || top == '-')
Â
         {
Â
             topPre=0;
Â
         }
Â
         if(top == '*' || top == '/' || top== '%')
Â
         {
Â
             topPre=1;
Â
         }
Â
         if(current == '+' || current == '-')
Â
         {
Â
             curPre=0;
Â
         }
Â
         if(current == '*' || current == '/' )
Â
         {
Â
             curPre=1;
Â
         }
Â
         if(topPre>=curPre)
Â
             return true;
Â
         else
Â
             return false;
Â
    }
Â
Â
GUI.java
Â
import java.awt.FlowLayout;
Â
import java.awt.GridLayout;
Â
import java.awt.event.ActionEvent;
Â
import java.awt.event.ActionListener;
Â
import java.util.EmptyStackException;
Â
import java.util.Stack;
Â
import javax.swing.JButton;
Â
import javax.swing.JFrame;
Â
import javax.swing.JLabel;
Â
import javax.swing.JOptionPane;
Â
import javax.swing.JPanel;
Â
import javax.swing.JTextField;
Â
import javax.swing.SwingConstants;
Â
public class GUI extends JFrame implements ActionListener
Â
{
Â
Â
           private static final long serialVersionUID = 1L;
Â
           JTextField userInput;
Â
    JLabel input,result,hint;
Â
    JPanel inputPanel,resultPanel;
Â
    JButton evaluate;
Â
    Stack<Object>stk;
Â
    GUI()
Â
    {
Â
         //Main GUI
Â
         super("Infix Expression Evaluator");
Â
         inputPanel=new JPanel(new FlowLayout());
Â
         resultPanel=new JPanel(new FlowLayout());
Â
         setLayout(new GridLayout(2,1));
Â
         userInput =new JTextField(30);
Â
         hint=new JLabel("Example: ( 3 * 3 ) 7. Make sure to leave spacing. Use only (, ), +, -, * , / ");
Â
         input=new JLabel("Enter Infix Expression:");
Â
         evaluate=new JButton("Evaluate");
Â
         evaluate.addActionListener(this);
Â
         result=new JLabel("Result:",SwingConstants.LEFT);
Â
         add(inputPanel);
Â
         add(resultPanel);
Â
         inputPanel.add(input);
Â
         inputPanel.add(userInput);
Â
         inputPanel.add(hint);
Â
         inputPanel.add(evaluate);
Â
         resultPanel.add(result);
Â
         stk=new Stack<Object>();
Â
    }
Â
Â
Â
    public static void main(String args[])
Â
    {
Â
         GUI gui=new GUI();
Â
         gui.setVisible(true);
Â
         gui.setSize(500,300);
Â
Â
Â
    }
Â
Â
    boolean isBalance(String exp)
Â
    {
Â
         int index = 0;
Â
         boolean fail = false;
Â
         int length=exp.length();
Â
         try
Â
         {
Â
             while (index < length && !fail)
Â
             {
Â
                  char ch = exp.charAt(index);
Â
                  switch(ch)
Â
                  {
Â
                       case '(':
Â
                       stk.push( new Character(ch) );
Â
                       break;
Â
                       case ')':
Â
                            char rightBrace=(char)stk.pop();
Â
                            if(rightBrace!='(')
Â
                                 fail=true;
Â
                            break;
Â
                       default:
Â
Â
Â
                       break;
Â
                  }
Â
                  index++;
Â
             }
Â
         }
Â
         catch(EmptyStackException e)
Â
         {
Â
             fail = true;
Â
         }
Â
         return stk.empty() && !fail;
Â
    }
Â
Â
Â
    public void actionPerformed(ActionEvent arg0)
Â
    {
Â
         InFix infix=new InFix();
Â
Â
Â
             String expression=userInput.getText();
Â
             //Call is evaluated if balance
Â
             if(isBalance(expression))
Â
             {
Â
                  try
Â
                  {
Â
                       int answer=infix.evaluate(expression);
Â
                       //Result display here
Â
                       if(answer==-1)
Â
                            result.setText("Result: Expresssion is not balanced.");
Â
                       else
Â
                            result.setText("Result: " +answer);
Â
                  }
Â
                  //Error message for dividing by 0
Â
                  catch(ArithmeticException e)
Â
                  {
Â
                       JOptionPane.showMessageDialog(this, "You cannot divide by Zero. Try again!",
Â
                                "ERROR",
Â
                                JOptionPane.ERROR_MESSAGE);
Â
                  }
Â
             }
Â
             //Error message if not balance
Â
             else
Â
                  result.setText("Result: Expresssion is not balanced.");
Â
             userInput.setText("");
Â
    }
Â
----------- Â ----------- H-----------ell-----------o S-----------ir/-----------Mad-----------am ----------- Th-----------ank----------- yo-----------u f-----------or -----------you-----------r i-----------nte-----------res-----------t a-----------nd -----------buy-----------ing----------- my----------- po-----------ste-----------d s-----------olu-----------tio-----------n. -----------Ple-----------ase----------- pi-----------ng -----------me -----------on -----------cha-----------t I----------- am----------- on-----------lin-----------e o-----------r i-----------nbo-----------x m-----------e a----------- me-----------ssa-----------ge -----------I w-----------ill----------- be----------- qu-----------ick-----------ly