473,382 Members | 1,305 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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.*;
  7. import javax.swing.event.*;
  9. public class Calculator extends JFrame {
  11.     JTextField textField;
  12.     private boolean startNumber= true;
  13.     private int resultTotal;
  14.     private String operator= "=";
  16.     public static void main(String[] args) {
  17.         Calculator calc = new Calculator();
  18.         calc.setVisible(true);
  19.     }
  21.     public Calculator() {
  22.         setTitle("Calculator");
  23.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  24.         setSize(300,400);
  25.         setLayout(new BorderLayout());
  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);
  35.         JPanel arithmeticFunctions= new JPanel();
  36.         arithmeticFunctions.setBackground(Color.WHITE);
  37.         arithmeticFunctions.setLayout(new GridLayout(5,1));
  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);
  56.         JPanel numberPad= new JPanel();
  57.         numberPad.setBackground(Color.WHITE);
  58.         numberPad.setLayout(new GridLayout(4,3));
  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);
  98.         JPanel cent= new JPanel();
  99.         cent.setBackground(Color.WHITE);
  100.         cent.setLayout(new FlowLayout());
  102.         JButton c= new JButton("C");
  103.         cent.add(c);
  104.         add(cent, BorderLayout.CENTER);
  105.     }
  107.     private void actionClear() {
  108.         startNumber= true;
  109.         textField.setText("0");
  110.         resultTotal=0;
  111.         operator= "=";
  112.     }
  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.     }
  127.     public class operatorListener implements ActionListener {
  128.         public void actionPerformed(ActionEvent e) {
  130.             if (startNumber)
  131.                 actionClear();
  132.             else
  133.                 startNumber= true;
  135.             try {
  136.                 String numOperator= textField.getText();
  137.                 int currentTotal= Integer.parseInt(numOperator);
  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.                 }
  152.                     if (operator.equals("=")) {
  153.                     resultTotal= currentTotal;
  154.                 }
  155.                 textField.setText("" + resultTotal);
  156.             }      
  158.             catch (NumberFormatException ex) {
  159.                 actionClear();
  160.             }
  162.             operator= e.getActionCommand();
  164.         }
  165.     }
  168. }
Nov 5 '07 #1
3 11810
539 512MB
Practice the core of String handling...

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...

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
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,

Nov 29 '07 #3
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

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

Similar topics

by: Michael | last post by:
Hello I am trying to write a Java-Program which converts a XML-file in a HTML. It should take the Transformation-file from the XML-file itself. Below find a possible XML-file: <?xml...
by: de_subhadeep | last post by:
Hi All, My program is running on a headless mode and I need to set the look and feel of my program but it gives me Headless Exception when I try to set the look and feel. The exception is as...
by: RobertMaas | last post by:
After many years of using LISP, I'm taking a class in Java and finding the two roughly comparable in some ways and very different in other ways. Each has a decent size library of useful utilities...
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
by: PieMan2004 | last post by:
Hi, ive been looking for a solid java community to help me when im tearing out my hair :) Basically ive constructed a GUI that has to represent the same look and functions of the typical windows...
by: erekose666 | last post by:
I have this program right now, but I need to modify it to output to the JTextPane. What I mean is, when someone clicks on the 1 button, it needs to output to the TextArea a 1. None of the add,...
by: oll3i | last post by:
package library.common; import java.sql.ResultSet; public interface LibraryInterface { public ResultSet getBookByAuthor(String author); public ResultSet getBookByName(String name);
by: helpwithcode | last post by:
Hi people, I am just learning java.I have been creating a project which involves JDBC Connectivity.I find that the statements, String string_dob=text_dob.getText(); //Converting string to...
by: zaidalin79 | last post by:
I have finally gotten my GUI to look like I want it to, but I am having trouble getting the calculations right. No matter what I put in there, it seems to calculate a large payment, and a very wrong...
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.