469,362 Members | 2,427 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,362 developers. It's quick & easy.

Java Swing Calculator with Precedence

This is a very primative code of a java swing calculator. I have assigned all the number buttons and the operator buttons and I can add, subtract, multiply, and divide two numbers together. However, my teacher wants the operators to follow the algebraic order of operations by chaining multiple operations. Such as, 7 + 4 * 2= 15. The operatorListener is the ActionListener for the operator buttons. Thanks for any help you can give me.



Expand|Select|Wrap|Line Numbers
  1. import java.awt.*;
  2. import javax.swing.*;
  3. import java.lang.*;
  4. import java.awt.event.*;
  5. import java.util.*;
  6.  
  7. import javax.swing.event.*;
  8.  
  9. public class Calculator extends JFrame {
  10.  
  11.     JTextField textField;
  12.     private boolean startNumber= true;
  13.     private int resultTotal;
  14.     private String operator= "=";
  15.  
  16.     public static void main(String[] args) {
  17.         Calculator calc = new Calculator();
  18.         calc.setVisible(true);
  19.     }
  20.  
  21.     public Calculator() {
  22.         setTitle("Calculator");
  23.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  24.         setSize(300,400);
  25.         setLayout(new BorderLayout());
  26.  
  27.         JPanel textPanel= new JPanel();
  28.         textPanel.setLayout(new FlowLayout());
  29.         textField= new JTextField("0", 20);
  30.         textField.setHorizontalAlignment(JTextField.RIGHT);
  31.         textField.setBackground(Color.WHITE);
  32.         textPanel.add(textField);
  33.         add(textPanel, BorderLayout.NORTH);
  34.  
  35.         JPanel arithmeticFunctions= new JPanel();
  36.         arithmeticFunctions.setBackground(Color.WHITE);
  37.         arithmeticFunctions.setLayout(new GridLayout(5,1));
  38.  
  39.         JButton divideButton= new JButton("/");
  40.         divideButton.addActionListener(new operatorListener());
  41.         arithmeticFunctions.add(divideButton);
  42.         JButton multiplyButton= new JButton("x");
  43.         multiplyButton.addActionListener(new operatorListener());
  44.         arithmeticFunctions.add(multiplyButton);
  45.         JButton subtractButton= new JButton("-");
  46.         subtractButton.addActionListener(new operatorListener());
  47.         arithmeticFunctions.add(subtractButton);        
  48.         JButton addButton= new JButton("+");
  49.         addButton.addActionListener(new operatorListener());
  50.         arithmeticFunctions.add(addButton);
  51.         JButton equalButton= new JButton("=");
  52.         equalButton.addActionListener(new operatorListener());
  53.         arithmeticFunctions.add(equalButton);
  54.         add(arithmeticFunctions, BorderLayout.EAST);
  55.  
  56.         JPanel numberPad= new JPanel();
  57.         numberPad.setBackground(Color.WHITE);
  58.         numberPad.setLayout(new GridLayout(4,3));
  59.  
  60.         JButton seven= new JButton("7");
  61.         seven.addActionListener(new numberListener());
  62.         numberPad.add(seven);
  63.         JButton eight= new JButton("8");
  64.         eight.addActionListener(new numberListener());
  65.         numberPad.add(eight);
  66.         JButton nine= new JButton("9");
  67.         nine.addActionListener(new numberListener());
  68.         numberPad.add(nine);
  69.         JButton four= new JButton("4");
  70.         four.addActionListener(new numberListener());
  71.         numberPad.add(four);
  72.         JButton five= new JButton("5");
  73.         five.addActionListener(new numberListener());
  74.         numberPad.add(five);
  75.         JButton six= new JButton("6");
  76.         six.addActionListener(new numberListener());
  77.         numberPad.add(six);
  78.         JButton one= new JButton("1");
  79.         one.addActionListener(new numberListener());
  80.         numberPad.add(one);
  81.         JButton two= new JButton("2");
  82.         two.addActionListener(new numberListener());
  83.         numberPad.add(two);
  84.         JButton three= new JButton("3");
  85.         three.addActionListener(new numberListener());
  86.         numberPad.add(three);
  87.         JButton zero= new JButton("0");
  88.         zero.addActionListener(new numberListener());
  89.         numberPad.add(zero);
  90.         JButton decimal= new JButton(".");
  91.         decimal.addActionListener(new numberListener());
  92.         numberPad.add(decimal);
  93.         JButton posNeg= new JButton("+/=");
  94.         numberPad.add(posNeg);
  95.         add(numberPad, BorderLayout.WEST);
  96.  
  97.  
  98.         JPanel cent= new JPanel();
  99.         cent.setBackground(Color.WHITE);
  100.         cent.setLayout(new FlowLayout());
  101.  
  102.         JButton c= new JButton("C");
  103.         cent.add(c);
  104.         add(cent, BorderLayout.CENTER);
  105.     }
  106.  
  107.     private void actionClear() {
  108.         startNumber= true;
  109.         textField.setText("0");
  110.         resultTotal=0;
  111.         operator= "=";
  112.     }
  113.  
  114.     public class numberListener implements ActionListener {
  115.         public void actionPerformed(ActionEvent e) {
  116.             String number= e.getActionCommand();
  117.             if (startNumber) {
  118.                 textField.setText(number);
  119.                 startNumber= false;
  120.             }
  121.             else {
  122.                 textField.setText(textField.getText()+ number);
  123.             }   
  124.         }
  125.     }
  126.  
  127.     public class operatorListener implements ActionListener {
  128.         public void actionPerformed(ActionEvent e) {
  129.  
  130.             if (startNumber)
  131.                 actionClear();
  132.             else
  133.                 startNumber= true;
  134.  
  135.             try {
  136.                 String numOperator= textField.getText();
  137.                 int currentTotal= Integer.parseInt(numOperator);
  138.  
  139.                 if (operator.equals("/")) {
  140.                     resultTotal /= currentTotal;
  141.                 }
  142.                 else if (operator.equals("x")) {
  143.                     resultTotal *= currentTotal;
  144.                 }
  145.                 else if (operator.equals("-")) {
  146.                     resultTotal -= currentTotal;
  147.                 }
  148.                 else if (operator.equals("+")) {
  149.                     resultTotal += currentTotal;
  150.                 }
  151.  
  152.                     if (operator.equals("=")) {
  153.                     resultTotal= currentTotal;
  154.                 }
  155.                 textField.setText("" + resultTotal);
  156.             }      
  157.  
  158.             catch (NumberFormatException ex) {
  159.                 actionClear();
  160.             }
  161.  
  162.             operator= e.getActionCommand();
  163.  
  164.         }
  165.     }
  166.  
  167.  
  168. }
Nov 5 '07 #1
3 10934
sukatoa
539 512MB
Practice the core of String handling...
M-multiplication
D-division
A-addition
S-subtraction

Assuming that you entered 7+8*2/4-6 and the answer is 5,

Here's the algo:

Capture the input "string 7+8*2/4-6"...
Convert it to character array...
seek for MDAS signs like +/*-...

for that example, obviously you will first encounter the '7', continue searching
by comparing the characters to MDAS operation...

Until you encounter +, for it is the third operation, try to get the element for your reference, like array[1] = '+' base on the assumption above...
then, continue loop...
until you get on the element that has the character ' * '...
When you are in that element, try to loop forward and backward until you incounter the next and previous operation and get that element for your reference again... for example, the '+' character is at array[2], '/' character is at array[5]...

Get the value between the * and / @ forward and also between * and + @backward...
Do the operation 8 * 2 = 16...
replace the character 8*2 into 16 in your character array...
looks like this: 7+16/4-6....
Loop again from array[0] and do the searching again... do the same way...
if no more ' * ' character, then the next character '/' is your target.... so on and so fort...

use:
for loop, while loop, array[]:comparing, etc....

you will expect more variables when you do this algo...
But when you got the idea, you can compress it...
Make it simple and sweet....


Hopefully, it helps =)
Nov 29 '07 #2
JosAH
11,448 Expert 8TB
Make it simple and sweet....

Hopefully, it helps =)
Sure, how about parentheses then? e.g. (12+4)/(11-3)

kind regards,

Jos
Nov 29 '07 #3
sukatoa
539 512MB
Same process!! but i think she will know later about that algorithm if she tries to do the first one...

If she does, she will probably design her own class/method to do the string manipulation regarding that scenario/situation...

I only gave her an example for manipulating simple inputs in the algo...
Nov 29 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Michael | last post: by
1 post views Thread by de_subhadeep | last post: by
73 posts views Thread by RobertMaas | last post: by
3 posts views Thread by PieMan2004 | last post: by
oll3i
reply views Thread by oll3i | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.