Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Please help with my calculator, 18 hours left to submit

  1. #1
    Junior Member
    Join Date
    Oct 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Please help with my calculator, 18 hours left to submit

    Tomorrow is the last day of University and I just have 1 lab left to submit which is my calculator, it's only worth 1%, but I've promised myself not to lose even 1% because I failed a paper last year by 1%, so I don't want that to happen again. There's 18 hours left to submit, so if someone could please help me it would be greatly appreciated. Thanks.

    So the problem is, that it does the most basic of calculations of multiples, plus and minus, I haven't added division yet, that will come later. If I try 5 * 5 = 25 obviously, but if I try something like 5 * 5 * 5 = 25, it wipes the 1st 5 and calculates the 2nd and 3rd 5. Same thing goes for 5 + 5 + 5 = 10. I need it to be able to do equations like -3 + 5, 4 * 4 + 6, 3 * 2 - 5, etc etc.

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Scanner;
     
    public class CalculatorPanel extends JPanel{
     
      private Calculator calc = new Calculator();
     
      //an array of buttons displayed on the calculator
      private JButton[] digitButtons;
     
      //output display for the calculator
      private JTextField display = new JTextField(10);
     
      //main method - sets up JFrame
      public static void main(String[]args){
     
        JFrame frame = new JFrame("Calculator");
        frame.setContentPane(new CalculatorPanel());
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
      }
     
      //constructor -- builds a GUI for a calculator
      public CalculatorPanel(){
     
        //create an array of button labels 
        String[] buttonLabels =  {"1", "2", "3", "4", "5", "6",
          "7", "8", "9", "C", "0", "=", "+", "-", "*"};
     
        //create an array of buttons
        digitButtons = new JButton[buttonLabels.length];
     
        //create an actionListener 
        ButtonListener  listener = new ButtonListener();
     
        // Create a 4 x 3 grid for placement of buttons. 
        JPanel buttonGrid = new JPanel();
        buttonGrid.setLayout(new GridLayout(5, 3));
     
        //create a button with each button label, add it to buttonGrid, and register the button as a listener
        for (int nextBut = 0; nextBut < digitButtons.length; nextBut++){
          digitButtons[nextBut] = new JButton(buttonLabels[nextBut]);
          buttonGrid.add(digitButtons[nextBut]);
          digitButtons[nextBut].addActionListener(listener);
        }
     
        //create a message for the user
        JLabel instruct = new JLabel("Press a button");
     
        //add the components to this JPanel
        setLayout(new BorderLayout());
        add(instruct, BorderLayout.NORTH);
        add(buttonGrid, BorderLayout.CENTER);
        add(display, BorderLayout.SOUTH);  
      }
     
      //represents a listener for button presses 
      private class ButtonListener implements ActionListener{
     
        //what to do when a button has been pressed */
        public void actionPerformed(ActionEvent aE){
     
          JButton whichButton = (JButton) aE.getSource();
          display.setText(  whichButton.getText());
     
          if ("+".equals(whichButton.getText())){
            calc.inOperator("+");
          }else if ("-".equals(whichButton.getText())){
            calc.inOperator("-");
          }else if ("*".equals(whichButton.getText())){
            calc.inOperator("*");
          }else if ("=".equals(whichButton.getText())){
            calc.inEquals();
            display.setText(calc.getResult());
          }else if ("C".equals(whichButton.getText())){
            calc.inClear();
            display.setText("0");
          }else{
            long i = 0;
            Scanner scan = new Scanner(whichButton.getText());
            i = scan.nextLong();
            calc.inDigit(i);
            display.setText(calc.getCurrentInput());
          }
     
        }
      }
     
    }

    public class Calculator{  
     
      private long currentInput;          //current input
      private long previousInput;         // previous input
      private long result;            // result of calculation
      private String lastOperator = "";  // keeps track of the last operator entered
     
     
      //new digit entered as integer value i - moves currentInput 1 decimal place to the left and adds i in "one's column"
      public void inDigit(long i){
     
        currentInput = (currentInput * 10) + i;
      }
     
      //operator entered  + - or *  
      public void inOperator(String op){
     
        previousInput = currentInput;      // save the new input as previous to get ready for next input
        currentInput = 0;
        lastOperator = op;                 // remember which operator was entered
      } 
     
     
       //equals operation sets result to previousInput + - or * currentInput (depending on lastOperator)
      public void inEquals(){
     
        if (lastOperator.equals("+")){
          result = previousInput + currentInput;     
        } else if (lastOperator.equals("-")) { 
          result = previousInput - currentInput;
        } else if (lastOperator.equals("*"))  {
          result = previousInput * currentInput;
        } 
        lastOperator = "";       // reset last operator to "nothing"
      }
     
      //clear operation
      public void inClear(){
     
        currentInput = 0;
        previousInput = 0;
        result = 0;
        lastOperator = "";
      } 
     
      //returns the current result
      public String getResult(){
     
        return Long.toString(result);  //converts int to String
      }
     
      //returns the previous input value
      public String getPreviousInput(){
     
        return Long.toString(previousInput);
      }
     
      //returns the current input value
      public String getCurrentInput(){
     
        return Long.toString(currentInput);
      }
     
    }


  2. #2
    Junior Member
    Join Date
    Oct 2014
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Please help with my calculator, 18 hours left to submit

    Your problem is that you are only performing calculation when the final '=' sign is pressed. In reality you shouldn't care when this occurs - the simple calculator cares not for BIDMAS or any other fundamentals and performs in-line calculations. So you should be performing the calculations as you go, i.e. every time a number is entered.

    Calculations are performed upon every number entry beyond and including that of the second. I would suggest the following hotfix, (please note: as this is a university assignment, I am NOT attaching the code!)

    Move your calculations out of inEquals and place them into inDigit, leave the 'lastOperator =' bit.

    Place them below the currentInput = line.
    Now you need to account for 2 situations:
    1) Result is empty.
    2) Result has been calculated, and you need to keep chain calculating.

    So your current statements should say be enclosed in an if () else () loop.

    If result is equal to zero
    - Perform current calculations.
    Else
    - The same statement as above except replace previousInput with result.

    Helps?

  3. #3
    Junior Member
    Join Date
    Oct 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Please help with my calculator, 18 hours left to submit

    Thanks for the fast response, I'll give it a go.

    EDIT: I tried what you said, maybe I'm bad at following instructions. It doesn't calculate now, it just says 'pressed ='.

    public class Calculator{  
     
      private int currentInput;          //current input
      private int previousInput;         // previous input
      private int result;            // result of calculation
      private String lastOperator = "";  // keeps track of the last operator entered
     
     
      //new digit entered as integer value i - moves currentInput 1 decimal place to the left and adds i in "one's column"
      public void inDigit(int i){
     
        currentInput = (currentInput * 10) + i;
     
        if (result == 0){
          if (lastOperator.equals("+")){
            result = previousInput + currentInput;     
          } else if (lastOperator.equals("-")) { 
            result = previousInput - currentInput;
          } else if (lastOperator.equals("*"))  {
            result = previousInput * currentInput;
          }
     
        }else
          if (lastOperator.equals("+")){
          result = result + currentInput;     
        } else if (lastOperator.equals("-")) { 
          result = result - currentInput;
        } else if (lastOperator.equals("*"))  {
          result = result * currentInput;
        } 
      }
     
     
    //operator entered  + - or *  
      public void inOperator(String op){
     
        previousInput = currentInput;      // save the new input as previous to get ready for next input
        currentInput = 0;
        lastOperator = op;                 // remember which operator was entered
      } 
     
     
    //equals operation sets result to previousInput + - or * currentInput (depending on lastOperator)
      public void inEquals(){
     
        lastOperator = "";       // reset last operator to "nothing"
      }
     
    //clear operation
      public void inClear(){
     
        currentInput = 0;
        previousInput = 0;
        result = 0;
        lastOperator = "";
      } 
     
    //returns the current result
      public String getResult(){
     
        return Integer.toString(result);  //converts int to String
      }
     
    //returns the previous input value
      public String getPreviousInput(){
     
        return Integer.toString(previousInput);
      }
     
    //returns the current input value
      public String getCurrentInput(){
     
        return Integer.toString(currentInput);
      }
    }
    Last edited by Synbios; October 9th, 2014 at 02:06 AM.

  4. #4
    Junior Member
    Join Date
    Oct 2014
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Please help with my calculator, 18 hours left to submit

    Can you post your current CalculatorPanel?

    Thanks

  5. #5
    Junior Member
    Join Date
    Oct 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Please help with my calculator, 18 hours left to submit

    It's the same as the first one, I haven't changed it. Thanks for the help.

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Scanner;
     
    public class CalculatorPanel extends JPanel{
     
      private Calculator calc = new Calculator();
     
      //an array of buttons displayed on the calculator
      private JButton[] digitButtons;
     
      //output display for the calculator
      private JTextField display = new JTextField(10);
     
      //main method - sets up JFrame
      public static void main(String[]args){
     
        JFrame frame = new JFrame("Calculator");
        frame.setContentPane(new CalculatorPanel());
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
      }
     
      //constructor -- builds a GUI for a calculator
      public CalculatorPanel(){
     
        //create an array of button labels 
        String[] buttonLabels =  {"1", "2", "3", "4", "5", "6",
          "7", "8", "9", "C", "0", "=", "+", "-", "*"};
     
        //create an array of buttons
        digitButtons = new JButton[buttonLabels.length];
     
        //create an actionListener 
        ButtonListener  listener = new ButtonListener();
     
        // Create a 4 x 3 grid for placement of buttons. 
        JPanel buttonGrid = new JPanel();
        buttonGrid.setLayout(new GridLayout(5, 3));
     
        //create a button with each button label, add it to buttonGrid, and register the button as a listener
        for (int nextBut = 0; nextBut < digitButtons.length; nextBut++){
          digitButtons[nextBut] = new JButton(buttonLabels[nextBut]);
          buttonGrid.add(digitButtons[nextBut]);
          digitButtons[nextBut].addActionListener(listener);
        }
     
        //create a message for the user
        JLabel instruct = new JLabel("Press a button");
     
        //add the components to this JPanel
        setLayout(new BorderLayout());
        add(instruct, BorderLayout.NORTH);
        add(buttonGrid, BorderLayout.CENTER);
        add(display, BorderLayout.SOUTH);  
      }
     
      //represents a listener for button presses 
      private class ButtonListener implements ActionListener{
     
        //what to do when a button has been pressed */
        public void actionPerformed(ActionEvent aE){
     
          JButton whichButton = (JButton) aE.getSource();
          display.setText(  whichButton.getText());
     
          if ("+".equals(whichButton.getText())){
            calc.inOperator("+");
          }else if ("-".equals(whichButton.getText())){
            calc.inOperator("-");
          }else if ("*".equals(whichButton.getText())){
            calc.inOperator("*");
          }else if ("=".equals(whichButton.getText())){
            calc.inEquals();
            display.setText(calc.getResult());
          }else if ("C".equals(whichButton.getText())){
            calc.inClear();
            display.setText("0");
          }else{
            long i = 0;
            Scanner scan = new Scanner(whichButton.getText());
            i = scan.nextLong();
            calc.inDigit(i);
            display.setText(calc.getCurrentInput());
          }
     
        }
      }
     
    }

  6. #6
    Junior Member
    Join Date
    Oct 2014
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Please help with my calculator, 18 hours left to submit

    You should be getting an error:
    Your inDigit method takes an integer value, but you are passing it a long.

    Change the variable types in Calculator back to Long?

    PS: Your instruction following was pleasantly accurate!
    Last edited by AGunner; October 9th, 2014 at 02:43 AM.

  7. #7
    Junior Member
    Join Date
    Oct 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Please help with my calculator, 18 hours left to submit

    I changed all int to long and Integer.toString to Long etc, but I'm still getting the same problem, I click 9 * 9 = then 'you pressed =', no errors or anything, just 'you pressed ='.

  8. #8
    Junior Member
    Join Date
    Oct 2014
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Please help with my calculator, 18 hours left to submit

    Are you sure

    I am testing your code with the variable types changed and it is working for me. 9*9*9=729.......

    The below is identical to your code?

    public class Calculator{  
     
      private long currentInput;          //current input
      private long previousInput;         // previous input
      private long result;            // result of calculation
      private String lastOperator = "";  // keeps track of the last operator entered
     
     
      //new digit entered as integer value i - moves currentInput 1 decimal place to the left and adds i in "one's column"
      public void inDigit(long i){
     
        currentInput = (currentInput * 10) + i;
     
        if (result == 0){
            if (lastOperator.equals("+")){
              result = previousInput + currentInput;     
            } else if (lastOperator.equals("-")) { 
              result = previousInput - currentInput;
            } else if (lastOperator.equals("*"))  {
              result = previousInput * currentInput;
            }
     
          }else
            if (lastOperator.equals("+")){
            result = result + currentInput;     
          } else if (lastOperator.equals("-")) { 
            result = result - currentInput;
          } else if (lastOperator.equals("*"))  {
            result = result * currentInput;
          } 
      }
     
     
    //operator entered  + - or *  
      public void inOperator(String op){
     
        previousInput = currentInput;      // save the new input as previous to get ready for next input
        currentInput = 0;
        lastOperator = op;                 // remember which operator was entered
      } 
     
     
    //equals operation sets result to previousInput + - or * currentInput (depending on lastOperator)
      public void inEquals(){
     
        lastOperator = "";       // reset last operator to "nothing"
      }
     
    //clear operation
      public void inClear(){
     
        currentInput = 0;
        previousInput = 0;
        result = 0;
        lastOperator = "";
      } 
     
    //returns the current result
      public String getResult(){
     
        return Long.toString(result);  //converts int to String
      }
     
    //returns the previous input value
      public String getPreviousInput(){
     
        return Long.toString(previousInput);
      }
     
    //returns the current input value
      public String getCurrentInput(){
     
        return Long.toString(currentInput);
      }
    }

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Scanner;
     
    public class CalculatorPanel extends JPanel{
     
      private Calculator calc = new Calculator();
     
      //an array of buttons displayed on the calculator
      private JButton[] digitButtons;
     
      //output display for the calculator
      private JTextField display = new JTextField(10);
     
      //main method - sets up JFrame
      public static void main(String[]args){
     
        JFrame frame = new JFrame("Calculator");
        frame.setContentPane(new CalculatorPanel());
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
      }
     
      //constructor -- builds a GUI for a calculator
      public CalculatorPanel(){
     
        //create an array of button labels 
        String[] buttonLabels =  {"1", "2", "3", "4", "5", "6",
          "7", "8", "9", "C", "0", "=", "+", "-", "*"};
     
        //create an array of buttons
        digitButtons = new JButton[buttonLabels.length];
     
        //create an actionListener 
        ButtonListener  listener = new ButtonListener();
     
        // Create a 4 x 3 grid for placement of buttons. 
        JPanel buttonGrid = new JPanel();
        buttonGrid.setLayout(new GridLayout(5, 3));
     
        //create a button with each button label, add it to buttonGrid, and register the button as a listener
        for (int nextBut = 0; nextBut < digitButtons.length; nextBut++){
          digitButtons[nextBut] = new JButton(buttonLabels[nextBut]);
          buttonGrid.add(digitButtons[nextBut]);
          digitButtons[nextBut].addActionListener(listener);
        }
     
        //create a message for the user
        JLabel instruct = new JLabel("Press a button");
     
        //add the components to this JPanel
        setLayout(new BorderLayout());
        add(instruct, BorderLayout.NORTH);
        add(buttonGrid, BorderLayout.CENTER);
        add(display, BorderLayout.SOUTH);  
      }
     
      //represents a listener for button presses 
      private class ButtonListener implements ActionListener{
     
        //what to do when a button has been pressed */
        public void actionPerformed(ActionEvent aE){
     
          JButton whichButton = (JButton) aE.getSource();
          display.setText(  whichButton.getText());
     
          if ("+".equals(whichButton.getText())){
            calc.inOperator("+");
          }else if ("-".equals(whichButton.getText())){
            calc.inOperator("-");
          }else if ("*".equals(whichButton.getText())){
            calc.inOperator("*");
          }else if ("=".equals(whichButton.getText())){
            calc.inEquals();
            display.setText(calc.getResult());
          }else if ("C".equals(whichButton.getText())){
            calc.inClear();
            display.setText("0");
          }else{
            long i = 0;
            Scanner scan = new Scanner(whichButton.getText());
            i = scan.nextLong();
            calc.inDigit(i);
            display.setText(calc.getCurrentInput());
          }
     
        }
      }
     
    }

  9. #9
    Junior Member
    Join Date
    Oct 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Please help with my calculator, 18 hours left to submit

    That's really weird, I'm gonna open up a fresh DrJava and try that code you've posted, lol.

    --- Update ---

    OK, that works, thanks heaps. Dunno why it wasn't working before. So, why did we take everything out of inEquals() and put it into inDigit() and put them in an if() else() loop?

  10. #10
    Junior Member
    Join Date
    Oct 2014
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Please help with my calculator, 18 hours left to submit

    Possibly DrJava was just getting involved in the last gasp effort by annoying you. Would be normal

    To understand why you want to calculate OUTSIDE of the inEquals() method consider the below:
    When a user inputs a number, there are two cases:
    1) It is the first number, in which case, do nothing.
    2) It is the nth number where n>1. In which case, there must be an operation to perform.
    2a) If n = 2, then result currently is not equal to anything, then we should add the two numbers together and assign result to them.
    2b) If n > 2, then result has a value, and we have a current input, plus we want to perform the new operation on them.

    If you only perform the math when an equals sign is input, then you will not be able to access anything but the values you have explicitly stored.

    As I say, it is something of a hotfix, ideally you would only store the a runningTotal, and operator, and a inputValue. Every time an inputValue was given (also when n = 1), you would say runningTotal(Operator)inputValue. And default the operator to a + and runningTotal to 0.

  11. #11
    Junior Member
    Join Date
    Oct 2014
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Please help with my calculator, 18 hours left to submit

    Thank you so much for your help, I really appreciate it. I've just been so busy trying to catch up with everything and all my assignments and with exams coming up. Tomorrow is the last day to get everything submitted and I just couldn't figure the Calculator out. Thanks.

  12. #12
    Junior Member
    Join Date
    Oct 2014
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Please help with my calculator, 18 hours left to submit

    No Problem. Your code was already very solid, just a small change to the logic that you were able to make yourself.

    Good luck with the exams

  13. The Following User Says Thank You to AGunner For This Useful Post:

    GregBrannon (October 9th, 2014)

Similar Threads

  1. JavaFx, Submit Button
    By ANNASBlackHat in forum JavaFX
    Replies: 1
    Last Post: March 30th, 2014, 02:46 PM
  2. Need help fast!!! 2 hours left!!! simple stack ADT
    By vysero in forum Object Oriented Programming
    Replies: 5
    Last Post: September 17th, 2012, 08:04 PM
  3. Help me PLEASe! I need to submit by 8.30am tmr!
    By shadz92 in forum What's Wrong With My Code?
    Replies: 109
    Last Post: July 29th, 2012, 07:51 PM
  4. need in few hours help me
    By erinbasim in forum Java Theory & Questions
    Replies: 3
    Last Post: February 2nd, 2010, 06:39 PM