GUI Calculator - Equals method

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 5217 Views - Last Post: 14 April 2008 - 08:21 AM Rate Topic: -----

#1 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

GUI Calculator - Equals method

Post icon  Posted 11 April 2008 - 07:42 PM

We're only supposed to work with the calc engine because everything else is already provided. i'm having problems figuring out how to make the equals method work. I thought an if or a switch statement might work but i don't know how to go about it.

/**
 * The main class of a simple calculator. Create one of these and you'll
 * get the calculator on screen.
 * 
 * @author David J. Barnes and Michael Kolling
 * @version 31 July 2000
 */
public class Calculator
{
	private CalcEngine engine;
	private UserInterface gui;

	/**
	 * Create a new calculator and show it.
	 */
	public Calculator()
	{
		engine = new CalcEngine();
		gui = new UserInterface(engine);
	}

	/**
	 * In case the window was closed, show it again.
	 */
	public void show()
	{
		gui.setVisible(true);
	}
}

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

/**
 * A graphical user interface for the calculator. No calculation is being
 * done here. This class is responsible just for putting up the display on 
 * screen. It then refers to the "CalcEngine" to do all the real work.
 * 
 * @author David J. Barnes and Michael Kolling
 * @version 31 July 2000
 */
public class UserInterface
	implements ActionListener
{
	private CalcEngine calc;
	private boolean showingAuthor;

	private JFrame frame;
	private JTextField display;
	private JLabel status;

	/**
	 * Create a user interface for a given calcEngine.
	 */
	public UserInterface(CalcEngine engine)
	{
		calc = engine;
		showingAuthor = true;
		makeFrame();
		frame.setVisible(true);
	}

	/**
	 * Make this interface visible again. (Has no effect if it is already
	 * visible.)
	 */
	public void setVisible(boolean visible)
	{
		frame.setVisible(visible);
	}

	/**
	 * Make the frame for the user interface.
	 */
	private void makeFrame()
	{
		frame = new JFrame(calc.getTitle());
		
		JPanel contentPane = (JPanel)frame.getContentPane();
		contentPane.setLayout(new BorderLayout(8, 8));
		contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10));

		display = new JTextField();
		contentPane.add(display, BorderLayout.NORTH);

		JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
			addButton(buttonPanel, "7");
			addButton(buttonPanel, "8");
			addButton(buttonPanel, "9");
			addButton(buttonPanel, "C");
			addButton(buttonPanel, "4");
			addButton(buttonPanel, "5");
			addButton(buttonPanel, "6");
			addButton(buttonPanel, "?");
			addButton(buttonPanel, "1");
			addButton(buttonPanel, "2");
			addButton(buttonPanel, "3");
			addButton(buttonPanel, "*");
			addButton(buttonPanel, "0");
			addButton(buttonPanel, "+");
			addButton(buttonPanel, "-");
			addButton(buttonPanel, "=");
		contentPane.add(buttonPanel, BorderLayout.CENTER);

		status = new JLabel(calc.getAuthor());
		contentPane.add(status, BorderLayout.SOUTH);

		frame.pack();
	}

	/**
	 * Add a button to the button panel.
	 */
	private void addButton(Container panel, String buttonText)
	{
		JButton button = new JButton(buttonText);
		button.addActionListener(this);
		panel.add(button);
	}

	/**
	 * An interface action has been performed. Find out what it was and
	 * handle it.
	 */
	public void actionPerformed(ActionEvent event)
	{
		String command = event.getActionCommand();

		if(command.equals("0") ||
		   command.equals("1") ||
		   command.equals("2") ||
		   command.equals("3") ||
		   command.equals("4") ||
		   command.equals("5") ||
		   command.equals("6") ||
		   command.equals("7") ||
		   command.equals("8") ||
		   command.equals("9"))
		{
			int number = Integer.parseInt(command);
			calc.numberPressed(number);
		}
		else if(command.equals("+"))
			calc.plus();
		else if(command.equals("-"))
			calc.minus();
		else if(command.equals("*"))
			calc.multiply();
		else if(command.equals("="))
			calc.equals();
		else if(command.equals("C"))
			calc.clear();
		else if(command.equals("?"))
			showInfo();

		redisplay();
	}

	/**
	 * Update the interface display to show the current value of the 
	 * calculator.
	 */
	private void redisplay()
	{
		display.setText("" + calc.getDisplayValue());
	}

	/**
	 * Toggle the info display in the calculator's status area between the
	 * author and version information.
	 */
	private void showInfo()
	{
		if(showingAuthor)
			status.setText(calc.getVersion());
		else
			status.setText(calc.getAuthor());

		showingAuthor = !showingAuthor;
	}
}

/**
 * The main part of the calculator doing the calculations.
 * 
 * @author  David J. Barnes and Michael Kolling
 * @version 0.1 (incomplete)
 */
public class CalcEngine
{
	// Put instance variables here.
	int entry=0;
	int result=0;
	int display;
	int lastEntry =0;
	

	/**
	 * Create a CalcEngine instance. Initialise its state so that it is ready 
	 * for use.
	 */
	public CalcEngine()
	{
		entry = display;
	}

	/**
	 * Return the value that should currently be displayed on the calculator
	 * display.
	 */
	public int getDisplayValue()
	{
		return entry;
	}

	/**
	 * A number button was pressed. Do whatever you have to do to handle it.
	 * The number value of the button is given as a parameter.
	 */
	public void numberPressed(int number)
	{
		entry = entry * 10 + number;
	}

	/**
	 * The 'plus' button was pressed. 
	 */
	public void plus()
	{
		lastEntry = entry;
		entry = 0;
		result = entry + lastEntry;
	}

	/**
	 * The 'minus' button was pressed.
	 */
	public void minus()
	{
		lastEntry = entry;
		entry = 0;
		result = entry - lastEntry;
	}

	/**
	 * The 'multiply' button was pressed.
	 */
	public void multiply()
	{
		lastEntry = entry;
		entry = 0;
		result = entry * lastEntry;
	}
	
	/**
	 * The '=' button was pressed.
	 */
	public void equals()
	{
	   
	}

	/**
	 * The 'C' (clear) button was pressed.
	 */
	public void clear()
	{
		entry = 0;
		lastEntry = 0;
		result = 0;
		display = 0;
	}

	/**
	 * Return the title of this calculation engine.
	 */
	public String getTitle()
	{
		return "Calculator";
	}

	/**
	 * Return the author of this engine. This string is displayed as it is,
	 * so it should say something like "Written by H. Simpson".
	 */
	public String getAuthor()
	{
		return "Written by Scott, Krutika, & Leah";
	}

	/**
	 * Return the version number of this engine. This string is displayed as 
	 * it is, so it should say something like "Version 1.1".
	 */
	public String getVersion()
	{
		return "Version 1.0";
	}
}


// some variable identifying last operation 


Is This A Good Question/Topic? 0
  • +

Replies To: GUI Calculator - Equals method

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5612
  • View blog
  • Posts: 14,686
  • Joined: 18-April 07

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 09:35 AM

This calcengine you have going here has some inherent problems with its way of even doing the simple operations. Lets take a look at what I mean...

public void minus()
{
        lastEntry = entry;
        entry = 0;
        result = entry - lastEntry;
}



This code will result in making "result" always a negative number. So if your entry was "25" result will be "-25" and then if you hit "5" result will then be "-5" not 20 as you might think. This is because your lines here boil down to the code...

result = 0 - entry;



Lets take a look at another one...

public void multiply()
{
        lastEntry = entry;
        entry = 0;
        result = entry * lastEntry;
}



This will result in making "result" always 0 no matter what number you put in. It boils down to the code...

result = 0 * entry;



I also noticed you don't have a divide method. Must have not gotten to it yet I am guessing.

What you need is a mechanism that stores the current result, a variable to hold the mode (modes being add, subtract, multiple, divide), and the current display. So to do a multiply you would do...

1. Enter a number
2. hit the multiply button which would do...
2a. Take the display, store it in result if result is empty, otherwise multiply against result
2b. Set a variable saying it is in mode multiply
3. User enters another number
4. Hits equals
4a. Takes result
4b. Finds out which mode it is in (in this case multiply)
4c. Takes display
4d. Calculates result * display
4e. Show result to screen
4f. Clear result and mode
5. Display result to screen

The beauty of this system is that....

1. It will allow you to chain calculations together (they can go number + number = result - number = result / number = result

2. It will show you the way for your equals method

3. You can calculate that feature where when you enter a number and hit a button (add, sub, mult, divide) and then hit the button again you can do the calculation on itself.... eg. 5 +++ will be 5 + 5 + 5 + 5 = 20.

That should give you the basis of making the calc engine work for you. Hope it helps!

"At DIC we be cold calculating code ninjas... especially when we put people in a meat locker... it is really cold then!" :snap:
Was This Post Helpful? 0
  • +
  • -

#3 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 01:36 PM

I'm still confused about how I could store a mode in a variable in 2b. As for storing the first entry in result, i did it with lastEntry instead. I just need to show how to set the next number i put into the calculator as the new entry number instead of going to 0.

Also, if I just set display = result for the equal methods, shouldn't it work?
public void equals()
	{
	   display = result;
	}


As for the divide, we only had to have three modes so I just picked add, minus, and multiply.
Was This Post Helpful? 0
  • +
  • -

#4 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5612
  • View blog
  • Posts: 14,686
  • Joined: 18-April 07

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 01:43 PM

Perhaps it would work, if like I said your other functions were doing what they were suppose to do. Then you could do display = result. But doesn't that hit you as odd to have a function purely to take one variable and set it to another? It is a waste and not good design.

When I was talking about storing the mode, you can store it anyway you want. You could store it as a string like "multiply" or you could store it as a number like 2 (which you know is multiply). Anyway you want to store it is fine, but when you hit equal you need to read the mode and know which calculation to make.

if (mode.equals("multiply")) {
    // Do code to multiply last entry by current entry
}



But whatever works for you. I was only showing one method you could do this as.

:)
Was This Post Helpful? 0
  • +
  • -

#5 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 01:53 PM

there's already a similar code in class userinterface:

else if(command.equals("+"))
calc.plus();
else if(command.equals("-"))
calc.minus();
else if(command.equals("*"))
calc.multiply();
else if(command.equals("="))
calc.equals();
else if(command.equals("C"))
calc.clear();
else if(command.equals("?"))
showInfo();
Was This Post Helpful? 0
  • +
  • -

#6 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5612
  • View blog
  • Posts: 14,686
  • Joined: 18-April 07

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 02:02 PM

I understand that, but what I am saying is your design is flawed. How can you do a multiply on button press when you don't know what the second operand is? Understand?

When you press "5" and then hit "*" you trigger your multiply and then what? When you get to equals you have trouble. Would it make sense to hit "5" then "*" put the calculator in multiply mode and wait for the second number which they type as "8" and then have equals go "I am in multiply mode so lets take the first entry 5 and multiply it by what they just typed in 8 and display 40".

:)
Was This Post Helpful? 0
  • +
  • -

#7 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 02:27 PM

thanks, i understand now. but still i'm not sure exactly what i'm storing in the variable multiply so it would go back into multiply mode. how can i bring it back to multiply mode?

public void multiply()
	{
		result *= entry;
		Boolean multiply = mode.equals("multiply");
		
	}
	
	/**
	 * The '=' button was pressed.
	 */
	public void equals()
	{
	   if (mode.equals("multiply")) 
	   {  
		   result = multiply * result;
		}  

	}

This post has been edited by kru: 12 April 2008 - 04:53 PM

Was This Post Helpful? 0
  • +
  • -

#8 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 12 April 2008 - 07:48 PM

I changed my coding so now it performs the calculations but doesn't show the second number. Also, I only have on digit for each number entered. It won't go to like "72" or "724" only "7".

/**
 * The main part of the calculator doing the calculations.
 * 
 * @author  David J. Barnes and Michael Kolling
 * @version 0.1 (incomplete)
 */
public class CalcEngine
{
	// Put instance variables here.
	private int digit1 = 0;
	private int digit2;
	private int total;
	int entry = -1;
	int lastEntry;
	int function = 4;

	/**
	 * Create a CalcEngine instance. Initialise its state so that it is ready 
	 * for use.
	 */
	public CalcEngine()
	{
	}

	/**
	 * Return the value that should currently be displayed on the calculator
	 * display.
	 */
	public int getDisplayValue()
	{
		if( total >= 1)
		{
			return total;
		}
		else if( entry == -1 )
		  {
			return digit1;
		  }
			else
			   return entry;
	}

	/**
	 * A number button was pressed. Do whatever you have to do to handle it.
	 * The number value of the button is given as a parameter.
	 */
	public void numberPressed(int number)
	{
		if( entry <= -1 )
		{
			entry = 0;
			entry = entry*10 + number;
			getDisplayValue();
		}
		  else
		  {
			lastEntry = lastEntry*10 + number;
			getDisplayValue();
		  }
	}

	/**
	 * The 'plus' button was pressed. 
	 */
	public void plus()
	{   
		function = 1;
	}

	/**
	 * The 'minus' button was pressed.
	 */
	public void minus()
	{
		function = 2;
	}
	
	public void multiply()
	{
		function = 3;
	}

	/**
	 * The '=' button was pressed.
	 */
	public void equals()
	{
		switch( function)
		{
			case 1: total = entry + lastEntry;
					lastEntry = total;
					entry = -1;
					getDisplayValue();
					break;
			case 2: total = entry - lastEntry;
					lastEntry = total;
					entry = -1;
					getDisplayValue();
					break;
			case 3: total = entry * lastEntry;
					lastEntry = total;
					entry = -1;
					getDisplayValue();
					break;
			case 4: entry = -1; lastEntry = 0; total = 0; break;
			default: entry = -1;
		}
	 }

	/**
	 * The 'C' (clear) button was pressed.
	 */
	public void clear()
	{
		 entry = -1;
		 lastEntry = 0;
		 total = 0;
		 getDisplayValue();
	}

	/**
	 * Return the title of this calculation engine.
	 */
	public String getTitle()
	{
		return "Calculator";
	}

	/**
	 * Return the author of this engine. This string is displayed as it is,
	 * so it should say something like "Written by H. Simpson".
	 */
	public String getAuthor()
	{
		return "";
	}

	/**
	 * Return the version number of this engine. This string is displayed as 
	 * it is, so it should say something like "Version 1.1".
	 */
	public String getVersion()
	{
		return "1";
	}
} 

This post has been edited by kru: 12 April 2008 - 07:49 PM

Was This Post Helpful? 0
  • +
  • -

#9 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 05:09 PM

Can someone please help me...
Was This Post Helpful? 0
  • +
  • -

#10 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 05:36 PM

View PostMartyr2, on 12 Apr, 2008 - 02:02 PM, said:

I understand that, but what I am saying is your design is flawed. How can you do a multiply on button press when you don't know what the second operand is? Understand?

When you press "5" and then hit "*" you trigger your multiply and then what? When you get to equals you have trouble. Would it make sense to hit "5" then "*" put the calculator in multiply mode and wait for the second number which they type as "8" and then have equals go "I am in multiply mode so lets take the first entry 5 and multiply it by what they just typed in 8 and display 40".

:)


Martyr that is`why I keep like a treasure my HP16C. You can offer me $ 10,000.00 for it, I won't sell it. Don't know what I will do when it will die.
Was This Post Helpful? 0
  • +
  • -

#11 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 07:51 PM

hey pbl (or anyone that knows Java), can you help me with my code? please look at post #8

This post has been edited by kru: 13 April 2008 - 08:19 PM

Was This Post Helpful? 0
  • +
  • -

#12 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 08:19 PM

View Postkru, on 13 Apr, 2008 - 07:51 PM, said:

hey pbl, can you help me with my code?


Sorry... I swear to God that I don't know how your calculator works... still using my good old HP16C
Can't even help my 15 years old son with it's Texas Instrument calculator from school
For a mysterious reason he cannot get the good answer but my calculator gives me the good result :-)

But, as far as I understand how these calculators work that is how I would do it:

When the "+", "-", "/" and "*" are pressed I would keep a flag to remember which operation was pressed.
like 0 = +, 1 = -, 2 = / and 3 = *

I would keep a "stack" of numbers entered

int number1 = 0, number2 = 0;

whenever a number is entered I would do:
number1 = number2;
number2 = new number entered;

whenever the "=" button is pressed i would do


result = number1 (saved operation) number2
display result
Was This Post Helpful? 0
  • +
  • -

#13 kru   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 29-February 08

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 08:27 PM

thanks for trying, but im still confused.
Was This Post Helpful? 0
  • +
  • -

#14 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 08:56 PM

View Postkru, on 13 Apr, 2008 - 08:27 PM, said:

thanks for trying, but im still confused.


Martyr you started... and I see you are reading this post... I let you finish to avoid cross-posting

This post has been edited by pbl: 13 April 2008 - 08:58 PM

Was This Post Helpful? 0
  • +
  • -

#15 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5612
  • View blog
  • Posts: 14,686
  • Joined: 18-April 07

Re: GUI Calculator - Equals method

Posted 13 April 2008 - 09:31 PM

Here are some modifications to the original calcengine.java. Notice we introduce a new operationmode variable which is int. The int will tell the calculator which mode it is in and do the appropriate calculation on the lastentry and the current entry to produce a result.

Check out the equals function to see how we test for each mode and do the appropriate calculation, but go back to each of the calc functions to see that we removed the assignment of result completely.

While this will not fix everything, it should show you the path we have been talking about.

CalcEngine.java...

/**
* The main part of the calculator doing the calculations.
*
* @author  David J. Barnes and Michael Kolling
* @version 0.1 (incomplete)
*/
public class CalcEngine
{
    // Put instance variables here.
    int entry=0;
    int result=0;
    int display;
    int lastEntry =0;

    // Notice we put in an operational mode variable
    // 1 = add, 2 = subtract, 3 = multiply and 4 = divide when you get that one done
    int operationmode = 0;
    

    /**
     * Create a CalcEngine instance. Initialise its state so that it is ready
     * for use.
     */
    public CalcEngine()
    {
        entry = display;
    }

    /**
     * Return the value that should currently be displayed on the calculator
     * display.
     */
    public int getDisplayValue()
    {
        return entry;
    }

    /**
     * A number button was pressed. Do whatever you have to do to handle it.
     * The number value of the button is given as a parameter.
     */
    public void numberPressed(int number)
    {
        entry = entry * 10 + number;
    }

    /**
     * The 'plus' button was pressed.
     */
    public void plus()
    {
        // set the last entry and put in "add mode"
        // clear the entry if you wish for display
        lastEntry = entry;
        operationmode = 1;
        entry = 0;
    }

    /**
     * The 'minus' button was pressed.
     */
    public void minus()
    {
        lastEntry = entry;
        operationmode = 2;
        entry = 0;
    }

    /**
     * The 'multiply' button was pressed.
     */
    public void multiply()
    {
        lastEntry = entry;
        operationmode = 3;
        entry = 0;
    }
    
    /**
     * The '=' button was pressed.
     */
    public void equals()
    {

        if (operationmode == 1) {
                // We are in add mode, so take last entry plus current display and add them
                entry += lastEntry;
        }
        else if (operationmode == 2) {
                // We are in subtract mode, so take the last entry minus the current display
                entry = lastEntry - entry;
        }
        else if (operationmode == 3) {
                // We are in multiply mode, so take the last entry multiply by current display
                entry *= lastEntry;
        }

        // Clear the mode variable to take it out of an operation mode
        operationmode = 0;
    }

    /**
     * The 'C' (clear) button was pressed.
     */
    public void clear()
    {
        entry = 0;
        lastEntry = 0;
        result = 0;
        display = 0;
    }

    /**
     * Return the title of this calculation engine.
     */
    public String getTitle()
    {
        return "Calculator";
    }

    /**
     * Return the author of this engine. This string is displayed as it is,
     * so it should say something like "Written by H. Simpson".
     */
    public String getAuthor()
    {
        return "Written by Scott, Krutika, & Leah";
    }

    /**
     * Return the version number of this engine. This string is displayed as
     * it is, so it should say something like "Version 1.1".
     */
    public String getVersion()
    {
        return "Version 1.0";
    }
}


// some variable identifying last operation



Play around with it a little and see how we moved the calculation load from the functions to the equals button. This may seem minor but in fact is profound since now we can wait for a second operand without trying to dirty any previous input or results.

:)
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2