Results 1 to 6 of 6
  1. #1
    Renegade85 is offline Member
    Join Date
    Nov 2007
    Posts
    25
    Rep Power
    0

    Default calculator not working

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;

    public class Calculator extends JFrame
    {
    //Create variables for Numbers being used
    private double temp1=0,temp2=0, currentDisplay=0;

    //
    final int MAX_INPUT_LENGTH = 20;
    final int INPUT_MODE = 0;
    final int RESULT_MODE = 1;
    final int ERROR_MODE = 2;
    int displayMode;

    boolean clearOnNextDigit, percent;
    double lastNumber;
    String lastOperator;

    // create calculator buttons
    private JButton jbtAdd = new JButton ("+");
    private JButton jbtSubtract = new JButton ("-");
    private JButton jbtDivide = new JButton ("/");
    private JButton jbtMultiply = new JButton ("*");
    private JButton jbtOne = new JButton ("1");
    private JButton jbtTwo = new JButton ("2");
    private JButton jbtThree = new JButton ("3");
    private JButton jbtFour = new JButton ("4");
    private JButton jbtFive = new JButton ("5");
    private JButton jbtSix = new JButton ("6");
    private JButton jbtSeven = new JButton ("7");
    private JButton jbtEight = new JButton ("8");
    private JButton jbtNine = new JButton ("9");
    private JButton jbtZero = new JButton ("0");
    private JButton jbtDot = new JButton (".");
    private JButton jbtEquals = new JButton ("=");

    // create text field for user to enter numbers in
    private JTextField jtfNumber = new JTextField (15);

    public Calculator ()
    {
    // create panel for buttons
    JPanel p1 = new JPanel ();

    //Set layout to gridlayout
    p1.setLayout (new GridLayout (4, 4));

    // add the buttons
    p1.add (jbtSeven);
    p1.add (jbtEight);
    p1.add (jbtNine);
    p1.add (jbtDivide);
    p1.add (jbtFour);
    p1.add (jbtFive);
    p1.add (jbtSix);
    p1.add (jbtMultiply);
    p1.add (jbtThree);
    p1.add (jbtTwo);
    p1.add (jbtOne);
    p1.add (jbtSubtract);
    p1.add (jbtZero);
    p1.add (jbtDot);
    p1.add (jbtEquals);
    p1.add (jbtAdd);
    jtfNumber.setEditable(false);

    // create panel p2 for holding text field and p1
    JPanel p2 = new JPanel (new BorderLayout ());
    p2.add ((jtfNumber), BorderLayout.NORTH);
    p2.add (p1, BorderLayout.CENTER);

    // add p2 to frame
    add (p2);

    // create actionlisteners
    ActionListener listener1 = new OneListener ();
    ActionListener listener2 = new TwoListener ();
    ActionListener listener3 = new ThreeListener ();
    ActionListener listener4 = new FourListener ();
    ActionListener listener5 = new FiveListener ();
    ActionListener listener6 = new SixListener ();
    ActionListener listener7 = new SevenListener ();
    ActionListener listener8 = new EightListener ();
    ActionListener listener9 = new NineListener ();
    ActionListener listener0 = new ZeroListener ();
    ActionListener listenerA = new AddListener ();
    ActionListener listenerS = new SubtractListener ();
    ActionListener listenerD = new DivideListener ();
    ActionListener listenerM = new MultiplyListener ();
    ActionListener listenerDot = new DotListener ();
    ActionListener listenerE = new EqualsListener ();

    // add actionlisteners to buttons
    jbtOne.addActionListener (listener1);
    jbtTwo.addActionListener (listener2);
    jbtThree.addActionListener (listener3);
    jbtFour.addActionListener (listener4);
    jbtFive.addActionListener (listener5);
    jbtSix.addActionListener (listener6);
    jbtSeven.addActionListener (listener7);
    jbtEight.addActionListener (listener8);
    jbtNine.addActionListener (listener9);
    jbtZero.addActionListener (listener0);
    jbtAdd.addActionListener (listenerA);
    jbtSubtract.addActionListener (listenerS);
    jbtDivide.addActionListener (listenerD);
    jbtMultiply.addActionListener (listenerM);
    jbtDot.addActionListener (listenerDot);
    jbtEquals.addActionListener (listenerE);
    }

    /** main method */
    public static void main (String [] args)
    {
    Calculator frame = new Calculator ();
    frame.setTitle ("Calculator");
    frame.setLocationRelativeTo (null); // center the frame
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.setSize (200, 250);
    frame.setVisible (true);
    frame.setResizable(false);
    }

    class OneListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(1);
    }
    }

    class TwoListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(2);
    }
    }

    class ThreeListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(3);
    }
    }

    class FourListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(4);
    }
    }

    class FiveListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(5);
    }
    }

    class SixListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(6);
    }
    }

    class SevenListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(7);
    }
    }

    class EightListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(8);
    }
    }

    class NineListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(9);
    }
    }

    class ZeroListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDigitToDisplay(0);
    }
    }

    class DivideListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    processOperator("/");
    }
    }

    class AddListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    processOperator("+");
    }
    }

    class SubtractListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    processOperator("-");
    }
    }

    class MultiplyListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    processOperator("*");
    }
    }

    class EqualsListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    processEquals();
    }
    }

    class DotListener implements ActionListener
    {
    public void actionPerformed (ActionEvent e)
    {
    addDecimalPoint();
    }
    }
    void setDisplayString(String s){
    jtfNumber.setText(s);
    }

    String getDisplayString (){
    return jtfNumber.getText();
    }

    void addDigitToDisplay(int digit){
    if (clearOnNextDigit)
    setDisplayString("");

    String inputString = getDisplayString();

    if (inputString.indexOf("0") == 0){
    inputString = inputString.substring(1);
    }

    if ((!inputString.equals("0") || digit > 0)
    && inputString.length() < MAX_INPUT_LENGTH){
    setDisplayString(inputString + digit);
    }


    displayMode = INPUT_MODE;
    clearOnNextDigit = false;
    }

    void addDecimalPoint(){
    displayMode = INPUT_MODE;

    if (clearOnNextDigit)
    setDisplayString("");

    String inputString = getDisplayString();

    // If the input string already contains a decimal point, don't
    // do anything to it.
    if (inputString.indexOf(".") < 0)
    setDisplayString(new String(inputString + "."));
    }

    void processSignChange(){
    if (displayMode == INPUT_MODE)
    {
    String input = getDisplayString();

    if (input.length() > 0 && !input.equals("0"))
    {
    if (input.indexOf("-") == 0)
    setDisplayString(input.substring(1));

    else
    setDisplayString("-" + input);
    }

    }

    else if (displayMode == RESULT_MODE)
    {
    double numberInDisplay = getNumberInDisplay();

    if (numberInDisplay != 0)
    displayResult(-numberInDisplay);
    }
    }

    void clearAll() {
    setDisplayString("0");
    lastOperator = "0";
    lastNumber = 0;
    displayMode = INPUT_MODE;
    clearOnNextDigit = true;
    }

    void clearExisting(){
    setDisplayString("0");
    clearOnNextDigit = true;
    displayMode = INPUT_MODE;
    }

    double getNumberInDisplay() {
    String input = jtfNumber.getText();
    return Double.parseDouble(input);
    }

    void processOperator(String op) {
    if (displayMode != ERROR_MODE)
    {
    double numberInDisplay = getNumberInDisplay();

    if (!lastOperator.equals("0"))
    {
    try
    {
    double result = processLastOperator();
    displayResult(result);
    lastNumber = result;
    }

    catch (DivideByZeroException e)
    {
    }
    }

    else
    {
    lastNumber = numberInDisplay;
    }

    clearOnNextDigit = true;
    lastOperator = op;
    }
    }

    void processEquals(){
    double result = 0;

    if (displayMode != ERROR_MODE){
    try
    {
    result = processLastOperator();
    displayResult(result);
    }

    catch (DivideByZeroException e) {
    displayError("Cannot divide by zero!");
    }

    lastOperator = "0";
    }
    }

    double processLastOperator() throws DivideByZeroException {
    double result = 0;
    double numberInDisplay = getNumberInDisplay();

    if (lastOperator.equals("/"))
    {
    if (numberInDisplay == 0)
    throw (new DivideByZeroException());

    result = lastNumber / numberInDisplay;
    }

    if (lastOperator.equals("*"))
    result = lastNumber * numberInDisplay;

    if (lastOperator.equals("-"))
    result = lastNumber - numberInDisplay;

    if (lastOperator.equals("+"))
    result = lastNumber + numberInDisplay;

    return result;
    }

    void displayResult(double result){
    setDisplayString(Double.toString(result));
    lastNumber = result;
    displayMode = RESULT_MODE;
    clearOnNextDigit = true;
    }

    void displayError(String errorMessage){
    setDisplayString(errorMessage);
    lastNumber = 0;
    displayMode = ERROR_MODE;
    clearOnNextDigit = true;
    }


    class DivideByZeroException extends Exception{
    public DivideByZeroException()
    {
    super();
    }

    public DivideByZeroException(String s)
    {
    super(s);
    }


    }
    }
    Anyone know why i getting an error (null pointer exception) when i push + - / * or =?

    Thanks for any help

  2. #2
    Renegade85 is offline Member
    Join Date
    Nov 2007
    Posts
    25
    Rep Power
    0

    Default

    Quote Originally Posted by Renegade85 View Post
    Anyone know why i getting an error (null pointer exception) when i push + - / * or =?

    Thanks for any help
    It's ok. I fixed it :D

  3. #3
    CaptainMorgan's Avatar
    CaptainMorgan is offline Moderator
    Join Date
    Dec 2007
    Location
    NewEngland, US
    Posts
    835
    Rep Power
    8

    Default

    Quote Originally Posted by Renegade85 View Post
    It's ok. I fixed it :D
    Renegade, it would be beneficial for the community if you provided how you derived your solution. Not to mention, it's said to be even beneficial for the code's owner to talk about the problem and how it was solved.
    Vote for the new slogan to our beloved Java Forums! (closes on September 4, 2008)
    Want to voice your opinion on your IDE/Editor of choice? Vote now!
    Got a little Capt'n in you? (drink responsibly)

  4. #4
    Renegade85 is offline Member
    Join Date
    Nov 2007
    Posts
    25
    Rep Power
    0

    Default

    The lastOperator String did not have an initial value and that was why i was getting a null pointer exception. That said, it's giving me problems again now. When you run the program, it doesn't work the way it should. It did work the first time i compiled it with an initial value for lastOperator but it's not working properly anymore.

    Everytime you push an operator now, it resets the display to 0.0. I don't know why it is doing this
    Last edited by Renegade85; 03-09-2008 at 12:42 AM.

  5. #5
    CaptainMorgan's Avatar
    CaptainMorgan is offline Moderator
    Join Date
    Dec 2007
    Location
    NewEngland, US
    Posts
    835
    Rep Power
    8

    Default

    Renegade, being short on time I'm afraid I can't get too deep into the logic of your code. What I've been able to see on the surface is that it works(computes) if you've already cleared the display. Have a look at sequence below.

    Java Code:
    input: 8, output: 8
    input: +, output: 0.0
    input: 4, output: 4
    input: *, output: 4.0
    input: 8, output: 8
    input: =, output: 32.0
    I would have a deeper look at the initial startup of the program... ie: why is it taking so long to get to the correct computations? Further note that after this simulation above, you can continue to input and get correct answers... so it seems like an error in the logic's initialization. Otherwise, the calculations work as they should.
    Vote for the new slogan to our beloved Java Forums! (closes on September 4, 2008)
    Want to voice your opinion on your IDE/Editor of choice? Vote now!
    Got a little Capt'n in you? (drink responsibly)

  6. #6
    Renegade85 is offline Member
    Join Date
    Nov 2007
    Posts
    25
    Rep Power
    0

    Default

    Quote Originally Posted by CaptainMorgan View Post
    Renegade, being short on time I'm afraid I can't get too deep into the logic of your code. What I've been able to see on the surface is that it works(computes) if you've already cleared the display. Have a look at sequence below.

    Java Code:
    input: 8, output: 8
    input: +, output: 0.0
    input: 4, output: 4
    input: *, output: 4.0
    input: 8, output: 8
    input: =, output: 32.0
    I would have a deeper look at the initial startup of the program... ie: why is it taking so long to get to the correct computations? Further note that after this simulation above, you can continue to input and get correct answers... so it seems like an error in the logic's initialization. Otherwise, the calculations work as they should.
    Ok, thanks. Will have a look later ;)

Similar Threads

  1. Java Calculator
    By aapanju in forum New To Java
    Replies: 3
    Last Post: 04-17-2008, 05:33 AM
  2. Java calculator decimal
    By cart1443 in forum New To Java
    Replies: 2
    Last Post: 04-16-2008, 01:19 PM
  3. Create a Calculator in Java
    By Albert in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 08:01 AM
  4. Swing Calculator
    By nemo in forum AWT / Swing
    Replies: 1
    Last Post: 05-28-2007, 11:07 AM
  5. Working With ANT
    By JavaForums in forum Eclipse
    Replies: 0
    Last Post: 04-26-2007, 08:16 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •