Results 1 to 5 of 5

Thread: Help me program a calculator in java

  1. #1
    Join Date
    Oct 2008
    Posts
    30

    Help me program a calculator in java

    Hello,

    I am new to java programming,
    I have an assignment for a simple java calculator.
    I found code over the net but I still want to do some more complex maths calculations. It will be more helpful if I could get a swing program.
    I have done the calculator in vb before but not sure for java.

    Thanks in advance.

  2. #2
    Join Date
    Oct 2008
    Posts
    37

    Re: Help me program a calculator in java

    Hey I have found this example for java calculator but its not a gui based program exactly but still I think this will help you create your own program using swing components.

    Code:
    import java.util.Scanner;
    
    public class calculator
    
    {
    public static void main(String[] args)
    {
    char answer;
    String input;
    int firstnumber;
    int secondnumber;
    
    
    System.out.println ("Welcome to the calculator!");
    System.out.println ("To multiply use m, to divide use d, to add use a, to subtract use s");
    
    Scanner keyboard = new Scanner(System.in);
    
    do
    {
    System.out.println ("Do you want to multiply, divide, add, or subtract? ");
    keyboard.nextLine();
    input = keyboard.nextLine();
    answer = input.charAt(0);
    
    if (answer == 'm')
    System.out.println ("Input first number: ");
    keyboard.nextLine();
    input = keyboard.nextLine();
    firstnumber = keyboard.nextInt();
    
    
    System.out.println ("Would you like another calculation (y/n)? ");
    keyboard.nextLine();
    input = keyboard.nextLine();
    answer = input.charAt(0);
    }
    while(answer == 'y')
    if(answer == 'n');
    System.exit(0);
    }
    }

  3. #3
    Join Date
    Oct 2008
    Posts
    31

    Re: Help me program a calculator in java

    Here is a simple example for GUI based java calculator I found:

    Code:
    /**
    This is a simple calculator program can any one take and use.
    @author sathish_ssmca
    @param nothing */
    import javax.swing.*;
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.awt.event.*;
    //<applet code=Calculator height=300 width=200></applet>
    public class Calculator extends JApplet {
    public void init() {
    CalculatorPanel calc=new CalculatorPanel();
    getContentPane().add(calc);
    }
    }
    
    class CalculatorPanel extends JPanel implements ActionListener {
    JButton
    n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
    static JTextField result=new JTextField("0",45);
    static String lastCommand=null;
    JOptionPane p=new JOptionPane();
    double preRes=0,secVal=0,res;
    
    private static void assign(String no)
    {
    if((result.getText()).equals("0"))
    result.setText(no);
    else if(lastCommand=="=")
    {
    result.setText(no);
    lastCommand=null;
    }
    else
    result.setText(result.getText()+no);
    }
    
    public CalculatorPanel() {
    setLayout(new BorderLayout());
    result.setEditable(false);
    result.setSize(300,200);
    add(result,BorderLayout.NORTH);
    JPanel panel=new JPanel();
    panel.setLayout(new GridLayout(4,4));
    
    n7=new JButton("7");
    panel.add(n7);
    n7.addActionListener(this);
    n8=new JButton("8");
    panel.add(n8);
    n8.addActionListener(this);
    n9=new JButton("9");
    panel.add(n9);
    n9.addActionListener(this);
    div=new JButton("/");
    panel.add(div);
    div.addActionListener(this);
    
    n4=new JButton("4");
    panel.add(n4);
    n4.addActionListener(this);
    n5=new JButton("5");
    panel.add(n5);
    n5.addActionListener(this);
    n6=new JButton("6");
    panel.add(n6);
    n6.addActionListener(this);
    mul=new JButton("*");
    panel.add(mul);
    mul.addActionListener(this);
    
    n1=new JButton("1");
    panel.add(n1);
    n1.addActionListener(this);
    n2=new JButton("2");
    panel.add(n2);
    n2.addActionListener(this);
    n3=new JButton("3");
    panel.add(n3);
    n3.addActionListener(this);
    minus=new JButton("-");
    panel.add(minus);
    minus.addActionListener(this);
    
    dot=new JButton(".");
    panel.add(dot);
    dot.addActionListener(this);
    n0=new JButton("0");
    panel.add(n0);
    n0.addActionListener(this);
    equal=new JButton("=");
    panel.add(equal);
    equal.addActionListener(this);
    plus=new JButton("+");
    panel.add(plus);
    plus.addActionListener(this);
    add(panel,BorderLayout.CENTER);
    }
    public void actionPerformed(ActionEvent ae)
    {
    if(ae.getSource()==n1) assign("1");
    else if(ae.getSource()==n2) assign("2");
    else if(ae.getSource()==n3) assign("3");
    else if(ae.getSource()==n4) assign("4");
    else if(ae.getSource()==n5) assign("5");
    else if(ae.getSource()==n6) assign("6");
    else if(ae.getSource()==n7) assign("7");
    else if(ae.getSource()==n8) assign("8");
    else if(ae.getSource()==n9) assign("9");
    else if(ae.getSource()==n0) assign("0");
    else if(ae.getSource()==dot)
    {
    if(((result.getText()).indexOf("."))==-1)
    result.setText(result.getText()+".");
    }
    else if(ae.getSource()==minus)
    {
    preRes=Double.parseDouble(result.getText());
    lastCommand="-";
    result.setText("0");
    }
    else if(ae.getSource()==div)
    {
    preRes=Double.parseDouble(result.getText());
    lastCommand="/";
    result.setText("0");
    }
    else if(ae.getSource()==equal)
    {
    secVal=Double.parseDouble(result.getText());
    if(lastCommand.equals("/"))
    res=preRes/secVal;
    else if(lastCommand.equals("*"))
    res=preRes*secVal;
    else if(lastCommand.equals("-"))
    res=preRes-secVal;
    else if(lastCommand.equals("+"))
    res=preRes+secVal;
    result.setText(" "+res);
    lastCommand="=";
    }
    else if(ae.getSource()==mul)
    {
    preRes=Double.parseDouble(result.getText());
    lastCommand="*";
    result.setText("0");
    }
    else if(ae.getSource()==plus)
    {
    preRes=Double.parseDouble(result.getText());
    lastCommand="+";
    result.setText("0");
    }
    
    }
    }

  4. #4
    Join Date
    Oct 2008
    Posts
    116

    Re: Help me program a calculator in java

    Here is a calculator program in swing.
    For developing a small calculator program in swing you need two different classes.

    • SwingCalculator.java
    • Calculator.java


    The SwingCalculator.java calls the Calculator.java class by JFrame frame = new Calculator(). All the methods and actions are to be performed in Calculator.java class.

    Please save the code as SwingCalculator.java

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
    class SwingCalculator {
       public static void main(String[] args) {
        JFrame frame = new Calculator();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        }
    }
    Here is the code of Calculator.java
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
      class Calculator extends JFrame {
      private final Font BIGGER_FONT = new Font("monspaced",
      Font.PLAIN, 20);
      private JTextField textfield;       
      private boolean   number = true;  
      private String    equalOp  = "=";  
      private CalculatorOp op = new CalculatorOp(); 
    
      public Calculator() {
      textfield = new JTextField("0", 12);
      textfield.setHorizontalAlignment(JTextField.RIGHT);
      textfield.setFont(BIGGER_FONT);
      
      ActionListener numberListener = new NumberListener();
      String buttonOrder = "1234567890 ";
      JPanel buttonPanel = new JPanel();
      buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
        for (int i = 0; i < buttonOrder.length(); i++) {
                String key = buttonOrder.substring(i, i+1);
                if (key.equals(" ")) {
                    buttonPanel.add(new JLabel(""));
                } else {
                    JButton button = new JButton(key);
                    button.addActionListener(numberListener);
                    button.setFont(BIGGER_FONT);
            buttonPanel.add(button);
                }
            }
      ActionListener operatorListener = new OperatorListener();
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(4, 4, 4, 4));
      String[] opOrder = {"+", "-", "*", "/","=","C"};
       for (int i = 0; i < opOrder.length; i++) {
        JButton button = new JButton(opOrder[i]);
        button.addActionListener(operatorListener);
        button.setFont(BIGGER_FONT);
      panel.add(button);
        }
       JPanel pan = new JPanel();
            pan.setLayout(new BorderLayout(4, 4));
            pan.add(textfield, BorderLayout.NORTH );
            pan.add(buttonPanel   , BorderLayout.CENTER);
            pan.add(panel , BorderLayout.EAST  );
            this.setContentPane(pan);
            this.pack();
            this.setTitle("Calculator");
            this.setResizable(false);
        }
            private void action() {
            number = true;         
            textfield.setText("0");
            equalOp  = "=";
            op.setTotal("0");
      }
      class OperatorListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
            if (number) {
                    action();
                    textfield.setText("0");
                } else {
                    number = true; 
                    String displayText = textfield.getText();
                    if (equalOp.equals("=")) {
                            op.setTotal(displayText);
                        } else if (equalOp.equals("+")) {
                            op.add(displayText);
                        } else if (equalOp.equals("-")) {
                            op.subtract(displayText);
                        } else if (equalOp.equals("*")) {
                            op.multiply(displayText);
                        } else if (equalOp.equals("/")) {
                            op.divide(displayText);
                        }
                       textfield.setText("" + op.getTotalString());
                       equalOp = e.getActionCommand();
                }
               }
               }
        class NumberListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                String digit = event.getActionCommand(); 
                if (number) {
                  textfield.setText(digit);
                  number = false;
                } else {
                 textfield.setText(textfield.getText() + digit);
                }
            }
        }
      public class CalculatorOp {
        
    private int total;   
    public CalculatorOp() {
            total = 0;
        }
       public String getTotalString() {
            return ""+total;
        }
       public void setTotal(String n) {
            total = convertToNumber(n);
        }
       public void add(String n) {
            total += convertToNumber(n);
       }
       public void subtract(String n) {
            total -= convertToNumber(n);
        }
       public void multiply(String n) {
            total *= convertToNumber(n);
        }
       public void divide(String n) {
            total /= convertToNumber(n);
        }
       private int convertToNumber(String n) {
            return Integer.parseInt(n);
        }
    }
    }
    The constructor new CalculatorOp() calls the CalculatorOp class. The Swing component JTextField is used to create textbox on which calculation is to be performed. JPanel arranges the numeric buttons in a panel. JButton is used to perform an action. OperatorListener class is called to perform action on operators, i.e, '+,-,*,/,='. The class NumberListener is called for numbers 0 to 9.

    I hope this helps you.

  5. #5
    Join Date
    Jun 2010
    Posts
    1

    Re: Help me program a calculator in java

    HELLO....
    I am new to java programming,
    I have an assignment for a simple java calculator.
    i have need a java program in awt using event.
    It will be more helpful if I could get a awt event handling program.
    I have done the calculator in awt ,but it contain few functions.
    i have need whole functions.
    Thanks in advance.

Similar Threads

  1. Java Calculator (Not GUI)
    By trixsareforkids in forum Software Development
    Replies: 1
    Last Post: 07-04-2011, 02:48 AM
  2. Calculator program using visual basic
    By Panchu in forum Software Development
    Replies: 3
    Last Post: 24-11-2009, 07:19 PM
  3. Link List Example in Java Sample program in Java
    By trickson in forum Software Development
    Replies: 2
    Last Post: 04-08-2009, 08:23 PM
  4. Replace calculator with Command Line Calculator
    By Eric B in forum Windows Software
    Replies: 3
    Last Post: 07-05-2009, 04:32 PM
  5. Java Swing Calculator Tutorial
    By hemanthjava in forum Software Development
    Replies: 0
    Last Post: 15-10-2006, 11:37 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,711,667,374.55253 seconds with 17 queries