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: | 337 Weeks Ago, 1 Day 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