Question
I have a java GUI calculator (class attached below) which isalmost 100% working properly. The program is having a stack poppingerror when I input -6
I have a java GUI calculator (class attached below) which isalmost 100% working properly. The program is having a stack poppingerror when I input -6 + 5 and if I enter it like (-6) + 5, etc. Ijust need a quick fix so the calculator can handle all types ofinput if a user was trying to "break" it (at the very least I needhandling of the negative numbers). the code is in Java
Code below
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class EvaalExpr extends JFrame implementsActionListener
{
JFrame frame = new JFrame("Expression Evaluator");
JPanel panel = new JPanel();
JLabel label = new JLabel("Expression:");
JTextField expression = new JTextField(25);
JButton button = new JButton("Calculate");
JButton clearButton = new JButton("Clear");
JLabel answerLable = new JLabel("Answer: ");
JTextField ansText = new JTextField(25);
JLabel inst1 = new JLabel("Enter an arithmetic expression, pleaseenter decimal");
JLabel inst2 = new JLabel("numbers like 0.25 instead of .25");
public EvaalExpr()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);//this size gives the window a properlayout
button.addActionListener(this);
clearButton.addActionListener(this);
panel.setLayout(new FlowLayout());
panel.add(label);
panel.add(expression);
expression.setBackground(Color.yellow);
panel.add(answerLable);
panel.add(ansText);
ansText.setBackground(Color.cyan);
frame.getContentPane().add(panel);
panel.add(button);
button.setBackground(Color.green);
panel.add(clearButton);
clearButton.setBackground(Color.red);
frame.setVisible(true);
expression.setText("Enter Expression Here");
ansText.setText("Answer Shows Here");
panel.add(inst1);
panel.add(inst2);
}
public static Double evaluate(String expression)
{
char[] tokens = expression.toCharArray();
Stack values = new Stack();//numbers stack
Stack operators = new Stack();//operators stack
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
while (i < tokens.length && tokens[i] >= '0'&& tokens[i] <= '9')
sbuf.append(tokens[i++]);
i--;
values.push(Double.parseDouble(sbuf.toString()));
}
else if (tokens[i] == '(')
operators.push(tokens[i]);
else if (tokens[i] == ')')
{
while (operators.peek() != '(')
values.push(operate(operators.pop(), values.pop(),values.pop()));
operators.pop();
}
else if (tokens[i] == '+' || tokens[i] == '-' || tokens[i] =='*' || tokens[i] == '/' || tokens[i] == '^')//operators
{
while (!operators.empty() && hasPrecedence(tokens[i],operators.peek()))
values.push(operate(operators.pop(), values.pop(),values.pop()));
operators.push(tokens[i]);
}
else if(tokens[i] == '.' )//handles decimal numbers
{
i++;
StringBuffer sbuf = new StringBuffer();
while (i < tokens.length && tokens[i] >= '0'&& tokens[i] <= '9')
sbuf.append(tokens[i++]);
i--;
values.push(values.pop()+Double.parseDouble("0."+sbuf.toString()));
}
}//end evalexpr
while (!operators.empty())
values.push(operate(operators.pop(), values.pop(),values.pop()));
return values.pop();
}
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 =='-'))
return false;
if ((op1 == '^') && (op2 == '+' || op2 == '-' || op2 == '*'|| op2 == '/'))
return false;
else
return true;
}
public static double operate(char op, double b, double a)
{
switch (op)
{
case '+':
return a + b;
case '^':
return Math.pow(a,b);
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if (action.equals("Clear"))
{
expression.setText("Enter Expression Here");
ansText.setText("Answer Shows Here");
}
else
{
System.out.println("Expression Evaluator");
System.out.println("Enter expression");
String input = expression.getText();
System.out.println(input);
Double res = evaluate(input);
ansText.setText(Math.round(res *10000000)/ 10000000.0 +"");//rounds as you instructed in class to use 10 million
}
}
public static void main(String[] args)
{
new EvaalExpr();
}
}//end program
Step by Step Solution
3.36 Rating (143 Votes )
There are 3 Steps involved in it
Step: 1
The issue youre experiencing is likely due to the way your code is handling neg...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started