I need to figure out what is wrong with this. I cannot get the add, subtract, di
ID: 3557453 • Letter: I
Question
I need to figure out what is wrong with this. I cannot get the add, subtract, division, and multiple buttons to work.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Calculator extends JApplet implements ActionListener
{
JTextArea total = new JTextArea("", 5, 25);
JScrollPane scrollingArea = new JScrollPane(total);
JLabel output = new JLabel();
double memVal = 0.0D;
double curVal = 0.0D;
Container content = getContentPane();
public void init()
{
content.setLayout(new BorderLayout(5, 5));
content.setBackground(Color.lightGray);
content.add("Center", makeButtons());
}
public void actionPerformed(ActionEvent ae)
{
// Local variables
JButton btn = (JButton) ae.getSource();
String arg = btn.getText(); // Key that was pressed
char c = arg.charAt(0); // First char of key caption
String s = output.getText(); // Current value of output
// "Special" keys operate on current value
if (arg.equals("Backspace")) backSpace(s);
else if (arg.equals("C")) clearAll();
else if (arg.equals("CE")) clearEntry();
else if (arg.equals("sqrt")) setCurVal(Math.sqrt(curVal));
else if (arg.equals("1/x")) setCurVal(1.0/curVal);
else if (arg.equals("+/-")) setCurVal(-curVal);
// Digit keys are always added to current value
else if (c >= '0' && c <= '9') setCurVal(s + c);
// Decimal point added only if not already in output
else if (c == '.')
{
if (s.indexOf(c) < 0) setCurVal(s + c);
}
// Handle all of the operator keys
else
{
switch (c)
{
case '/':
memVal /= curVal;
break;
case '*':
memVal *= curVal;
break;
case '-':
memVal -= curVal;
break;
case '+':
memVal += curVal;
break;
case '%':
memVal %= curVal;
break;
case '=':
memVal = curVal;
total.append(padText("============= ",25));
break;
}
// Display results on the TextArea named total
String memstr = "" + curVal + " " + c + " ";
total.append(padText(memstr,25));
memstr = "" + memVal + " ";
total.append(padText(memstr,25));
// Clear the output Label
curVal = 0;
output.setText("");
}
}
// ----------------------------------------------------------
// These are utility methods
// ----------------------------------------------------------
String padText(String s, int size)
{
String temp = " " + s;
return temp.substring(temp.length() - size);
}
void backSpace(String s)
{
if (s.length() <= 0)
{
return;
}
s = s.substring(0, s.length() - 1);
setCurVal(s);
}
void clearAll()
{
total.setText("");
output.setText("");
curVal = (memVal = 0.0D);
}
void clearEntry()
{
output.setText("");
curVal = 0.0D;
}
void setCurVal(String s)
{
output.setText(s);
try
{
curVal = new Double(s).doubleValue();
}
catch (NumberFormatException ae) {}
}
void setCurVal(double newValue)
{
curVal = newValue;
output.setText("" + newValue);
}
JPanel makeButtons()
{
JPanel p = new JPanel(new BorderLayout(5, 5));
JPanel p1 = new JPanel(new BorderLayout(5, 5));
JPanel p2 = new JPanel(new BorderLayout(5, 5));
JPanel p3 = new JPanel(new GridLayout(1, 3, 5, 5));
JPanel p4 = new JPanel(new GridLayout(4, 5, 5, 5));
JPanel p5 = new JPanel(new BorderLayout(5, 5));
JButton Backspace = new JButton("Backspace");
JButton CE = new JButton("CE");
JButton Clear = new JButton("C");
Backspace.addActionListener(this);
CE.addActionListener(this);
Clear.addActionListener(this);
p3.setForeground(new Color(232, 0, 0));
p3.setFont(new Font("Dialog", 0, 12));
p3.add(Backspace);
p3.add(CE);
p3.add(Clear);
JButton zero = new JButton("0");
JButton JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
JButton five = new JButton("5");
JButton six = new JButton("6");
JButton seven = new JButton("7");
JButton eight = new JButton("8");
JButton nine = new JButton("9");
JButton addition = new JButton("+");
JButton subtract = new JButton("-");
JButton multiply = new JButton("*");
JButton divide = new JButton("/");
JButton sqrt = new JButton("sqrt");
JButton xOver1 = new JButton("1/x");
JButton plusOrMinus = new JButton("+/-");
JButton decimal = new JButton(".");
JButton eql = new JButton("=");
JButton percent = new JButton("%");
zero.addActionListener(this);
p4.setForeground(new Color(0, 0, 235));
p4.setFont(new Font("Dialog", 0, 14));
zero.addActionListener(this);
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
addition.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
sqrt.addActionListener(this);
xOver1.addActionListener(this);
plusOrMinus.addActionListener(this);
decimal.addActionListener(this);
eql.addActionListener(this);
p4.setForeground(new Color(0, 0, 235));
p4.setFont(new Font("Dialog", Font.PLAIN, 14));
p4.add(seven);
p4.add(eight);
p4.add(nine);
p4.add(divide);
p4.add(sqrt);
p4.add(four);
p4.add(five);
p4.add(six);
p4.add(multiply);
p4.add(percent);
p4.add(one);
p4.add(two);
p4.add(three);
p4.add(subtract);
p4.add(xOver1);
p4.add(zero);
p4.add(plusOrMinus);
p4.add(decimal);
p4.add(addition);
p4.add(eql);
output.setBackground(Color.white);
output.setForeground(Color.black);
output.setFont(new Font("Courier", 1, 18));
total.setBackground(new Color(255, 255, 128));
total.setForeground(Color.black);
total.setFont(new Font("Courier", 1, 14));
p5.add("Center", scrollingArea);
p5.add("South", output);
p2.add("North", p3);
p2.add("Center", p4);
p1.add("North", p5);
p1.add("Center", p2);
p.setFont(new Font("Helvetica", 0, 6));
p.add("North", new Label(" "));
p.add("East", new Label(" "));
p.add("West", new Label(" "));
p.add("South", new Label(" "));
p.add("Center", p1);
return p;
}
}
Explanation / Answer
The thing you need is to evaluate expression you give through input
For suppose 6*9/3 should give 36.
As per your code, you need to change the total switch statement as curVal and memVal are used incosistantly . Only two operands are being evaluated at a time. try to put the following Arithmetic expression evaluation code in your code . Final thing i wanna say is that the code you 've given fits only to single arithmetic operation and only for two operands. I cannot change your code as it needs to be changed in all segments.
Arithmetic evaluation is all u need !
It is given below.
/* A Java program to evaluate a given expression where tokens are separated
by space.
Test Cases:
"10 + 2 * 6" ---> 22
"100 * 2 + 12" ---> 212
"100 * ( 2 + 12 )" ---> 1400
"100 * ( 2 + 12 ) / 14" ---> 100
*/
import java.util.Stack;
public class EvaluateString
{
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
// Stack for numbers: 'values'
Stack<Integer> values = new Stack<Integer>();
// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();
for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
if (tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.toString()));
}
// Current token is an opening brace, push it to 'ops'
else if (tokens[i] == '(')
ops.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')')
{
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/')
{
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!ops.empty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
// Top of 'values' contains result, return it
return values.pop();
}
// Returns true if 'op2' has higher or same precedence as 'op1',
// otherwise returns false.
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a)
{
switch (op)
{
case '+':
return 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;
}
// Driver method to test above methods
public static void main(String[] args)
{
System.out.println(EvaluateString.evaluate("10 + 2 * 6"));
System.out.println(EvaluateString.evaluate("100 * 2 + 12"));
System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 )"));
System.out.println(EvaluateString.evaluate("100 * ( 2 + 12 ) / 14"));
}
}
Output :