Delphi Programming
Advertisement

This tutorial is intended for Delphi beginners who have a somewhat steady knowledge of both the components and simple coding within Delphi. Basic processes like naming objects will not be fully described. Programming a calculator is a great way to begin learning any programming language. It offers a practical project that includes many (but not too many) elements of the language. This is just one way you could code a calculator in Delphi. There are probably many ways to this, and I fully challenge you to find new and creative methods of doing such. This specific calculator will be able to handle four mathematical functions with two numbers. Let's begin.


So the first thing we should do is open Delphi (I will be using Delphi 5, but this tutorial will likely be compatible with most versions of Delphi.) You will be presented with a new project titled "Project 1." The project includes three detached windows: the Object Inspector, the unit windo, and the form. I will assume you are fairly familiar with the basic layout of Delphi; if not, I suggest you first read a few of the articles found over the internet for brand new Delphi programmers. Now let's build the design for the calculator.


The Calculator Design

Calculator Design

My Calculator Layout

For this calculator, we will be using buttons, labels, edit boxes, and panels from the component palette. All of these components are found in the "Standard" tab of the component palette. We will want an edit box at the very top of the calculator,buttons to add numbers to this edit box, buttons to signify certain mathematical funcitons, a label to display our answer. You should arrange these components in any way that appeals to you, but I will offer my design for you to follow. My design can be seen to the right.

Here is a list of the components I used to create my calculator:

  • 19 Buttons (10 for numbers 0-9; 4 for the mathetical functions addition, subtraction, multiplication, and division; a clear value button, a negative/positive button, an enter button, and a reset button.)
  • 1 Edit Box for user input
  • 1 Label to display the answer
  • 1 Panel for aesthetic purposes.

I suggest you use all the buttons and other components I do for coding purposes, but as said before, I also recommend you to design your calculator in any way you feel appropriate.


You can change what is displayed on the buttons and label by clicking on an individual button or the label and going to the Object Inspector. You will see a list of paramaters and one will be called "Caption." Click on the white panel directly right of the Caption box and type in the caption you would like to see displayed. You can also change the font displayed by the buttons by changing the many options listed under the "Font" parameter or by simply selecting the white edit box right of the Font box and clicking on the small button that is labeled "..." This should bring up a font palette that will make adjusting the font much easier. You can change the font to both the label and edit box in this way, also. To change the text in the edit box, you will need to adjust the "Text" paramater. I have mine blank, and I suggest you do the same.


Let's go ahead and compile and test our "calculator." Do this by pressing F9 or selecting Run>Run. As you can see it looks like what we built, but it is completely useless as far as being a calculator. That's where the coding comes in.


Coding Your Calculator

The Number Buttons

We will start with the most basic coding involved with this calculator: the number buttons. Their sole purpose is to make the numbers that appear on their surface to also appear in the edit box. Before we begin, let's thoroughly plan what we want to occur when each button is pressed. We want the number to be placed into the edit box behind any numbers that already exist in the edit box. To do this, we need to create an "OnClick" event. Select your number "1" button and go to the Object Inspector, click on the "Events" tab and double click the white box to the right of the "OnClick" parameter. This will bring up your unit with all of the coding. Because you double clicked this box, some coding has already been created for you. This is the event holder. We will place our code within this code block between the newly created "begin" and "end;".

Here is the code I used for my number "1":

procedure TCalculatorForm.OneClick(Sender: TObject);
begin
     NumberEdit.Text := NumberEdit.Text + '1';
end;

Here is a breakdown of this code:

  • "NumberEdit.Text" refers to the edit box we placed at the top of the form. (I renamed all of my objects, and I encourage you to do so, too, but I will not be giving you all the names of my objects until we encounter them in code. To change the name of an object, go to the Objhect Inspector with that object selected and change the "Name" parameter.)
  • The " := " indicates that NumberEdit.Text will be changed in some way.
  • What comes after " := " (" NumeberEdit.Text + '1'; ") indicates what the original "NumberEdit.Text" will be changed to.
  • By placing the name of the edit box in the portion of the code that indicates what the edit box will be changed to, we insure that the numbers we may have already punched in will stay inside the edit box when we add another number. For example if we have already punched in a 3 on our calculator, we will be able to make this value 31 by simply pressing the 1. Simple as that.
  • The " + '1' " portion of the code gives the code its ability to add a one to the edit box. The 1 is surrounded by apostrophes because it is not something the coding would recognize otherwise. All undeclared wording such as this will have to be placed inside apostrophes.

Hopefully, you understand the reasoning behind this code now. Now you can create shell code for an OnClick event for each number button by doing the process described here. (You can also double click the button itself to create an OnClick event). Inside that code block paste the code for the "1" button and change the value of " + '1' " to whatever number needs to be added to the edit box when that specific button is clicked.


For example the number 2 button's code should read as such:

procedure TCalculatorForm.TwoClick(Sender: TObject);
begin
     NumberEdit.Text := NumberEdit.Text + '2';
end;

(As you can see I changed both the names of my form and the number two button.)


Once you have the event holder and coding in place for every number button and the decimal point (just replace '1' with '.'), let's go ahead and run our project. If everything went right, it should compile, and we should be able to add numbers to the edit box by clicking each button.

Hint: You will not be able to copy and paste my code directly if you did not name your objects exactly as I did. A copy of the number button code that does not have anything renamed would be like this:

procedure TForm1.Button1Click(Sender: TObject);
begin
     Edit1.Text := Edit1.Text + '1'.
end;

The Negative Button

If you were able to get your number buttons running, you are ready to move on to the negative/positive button. First, create an OnClick event holder for this button. Now let's think about exactly what we want this button to accomplish. It should turn the value of the edit box's number to a negative if the value is positive. If the value is already negative, we want the returned value to be positive. While it may sound like we will need to build an if then else statement, it is actually easier than that with some simple math. When you multiply a positive times a negative, you will get a negative. When you multiply a negative times a negative, you will get a positive. With that in mind, it will be much simpler to just multiply whatever value is found within the edit box by -1.

Here's the code for the negative button with an explanation following it:

procedure TCalculatorForm.NegativeClick(Sender: TObject);
var
     OriginalNumber: real;
     TextNumber: string;
begin
     OriginalNumber := -(StrToFloat(NumberEdit.Text));
     TextNumber := FormatFloat('0.##########', OriginalNumber);
     NumberEdit.Text := TextNumber;
end;

Explanation:

  • Immediately after the declaration of the procedure, the code declares two "local" variables. These variables can only be seen by this specific procedure and would not be able to be used by any other procedure/event. We will discuss "global" variables shortly.
  • "OriginalNumber" is a real variable, meaning it is a number value. Any number value can be assigned to this variable including 10 or 1.61803399.
  • In contrast to this, NumberEdit.Text (all of the text that is entered into the edit box at the top of the calculator) is a string variable; however, to make our mathematical function (multiplying by -1) work, we need to use a real variable. To do this, we use the StrToFloat function. This function turns a string variable into a floating point value (real) variable. While we used this function, we also multiplied by -1 but just used a negative sign.
  • As seen in the top line of the statement (the statement is everything between begin and end;), we set our NumberEdit.Text that has been turned into a real variable and multiplied by -1 equal to OriginalNumber, a real variable. We now want to put this value back into the edit box; to do such, we will need to turn the real variable back into a string variable.
  • The function FomatFloat formats real variables into string variables. We have used this function in the second line of the statement, setting the function and its parameters equal to the string variable TextNumber. Inside the parentheses of FormatFloat, we have two separate items. The first is most likely the most unrecognizeable. The first item is " '0.##########' '''". This is an essential part of the FormatFloat function. It is an indicator of exactly how the new string variable should be formatted, giving information on how many number places should be included both before and after the decimal point. The zero before the decimal point indicates that we always want at least one number before the decimal point. If there are anymore numbers before the decimal point included when the calculation is finished, they will also be added to the string. The #s behind the decimal point indicate that those number places are optional. If a value happens to include a number in any of these place holders, they will be included in the string. The last part of the FormatFloat function is the real variable OriginalNumber. This simply means that OriginalNumber is the variable that will be formatted.
  • The last line of the statement simply means that the value of the string variable "TextNumber" should become the the text of NumberEdit.


The Math Function Buttons

The next coding we will add to our program is the coding needed to create the mathematical functions buttons. I will give you the code and walk-through for the addition button and then give a quick overview on how to modify that code for the subtraction, multiplication, and division buttons. First, create an OnClick event holder for the addition buttonm, and then add code similiar to this:

procedure TCalculatorForm.AdditionClick(Sender: TObject);
begin
     Math := 'Add';
     FNumber := StrToFloat(NumberEdit.Text);
     NumberEdit.Text := ;
end;

Here's an explanation:

  • The first thing that you might notice is that there are two new variables that were not declared within the procedure: "Math" and "FNumber". These were not declared because they will need to be used in another procedure coming up, so we will need to be delcared with a "global scope." This means they will be accessible to all procedures within the unit. To declare a variable with a global perspective, declare it in the same format as delcaring a variable in a procedure, but do so directly beneath the word "Implementation" found towards the top of the unit. "Math" is a string variable, "FNumber" is a real variable.
  • The first line of the statement simply sets the variable Math equal to the string 'Add'. Notice 'Add' is between apostrophes; this is because it is an actual string not an identifier/variable.
  • The second line of the statement sets the real variable FNumber equal to the function of StrToFloat(NumberEdit.Text). This is similiar to the StrToFloat function found in the negative button explanation. We will eventually need FNumber to be a floating point value, so the conversion is done in this step. It also allows us to set FNumber equal to a value and keep that value stored in memory until it is needed again.
  • The last line of this statement sets the edit box back to blank, so another number can be added.



To modify this code for any of the mathematical function buttons, change the string for what the variable Math equals. If the function is subtraction, set Math equal to 'Subtract'. Here are the strings I used:

  • Addition ... Math := 'Add'
  • Subtraction ... Math := 'Subtract'
  • Multiplication ... Math := 'Math'
  • Division ... Math := 'Divide'

You will see how these strings will initiate the correct function in the next step.


The Enter Button

The enter button is an extremely vital part of the calculator and one of the more complicated coding structures. In this calculator, we will use if then statements to differentiate between the math functions that need to be performed in the calculation. I will give you the coding for the overall procedure and one of the if then statements and an explanation; then, I will explain how to implement if then statements for the other math functions.

Here's the coding for an OnClick event of the Enter button:

procedure TCalculatorForm.EnterClick(Sender: TObject);
var
    Text : string;
    Answer, SNumber : real;

begin
  SNumber := StrToFloat(NumberEdit.Text);

  begin
    if Math = 'Add' then
      Answer := FNumber + SNumber;
      Text := FormatFloat('0.#####', Answer);
      Equals.Caption := '= ' + Text;
      NumberEdit.Text := ;
  end;

Explanation:

  • In this procedure, there are three variables declared: Text (a string variable), answer (a real variable), and SNumber (a real variable).
  • At the beginning of the statement, you will find the variable SNumber is set equal to the function StrToFloat(NumberEdit.Text). By now, this process should be fairly straightforward. SNumber is now the second number that will be included in the calculation, and it is formatted as a floating-point value.
  • The next line begins our first if then statement. An if then statement sets a condition that must be met for the process following it to be completed. In our if then statement, the variable Math must equal 'Add' (this is where our varied string values comes in). If Math does equal 'Add', then the four lines of code following the conditional statement will be executed by the program. If the conditional statement is not met, those four lines are skipped over.
  • Assuming the condition is met, the program will first read the top line. This line sets the real variable Answer equal to FNumber + SNumber. This is the heart of the addition function. The variable Answer will be set equal to the sum of FNumber and SNumber. FNumber and SNumber were pre-determined by the values inputted into the calculator's edit box.
  • The string variable "Text" is then set equal to the function FormatFloat('0.#####', Answer). This process takes a floating point value (Answer) and turns it into a string value with a defined format ('0.#####').
  • The answer of the calculation is then displayed in the label at the bottom of the calculator (Equals.Caption) through the process on the third line. The caption paramater of the label "Equals" is set equal to both the string value '= ' and the value of the string variable Text.
  • In the last line of the if then statement the edit box is set to blank so another calculation can be made.


To format this code for any of the mathematical functions just change the conditional statement so that "Math" equals the string you assigned to that specific mathematical function. Also, change the first line of the if then statement, so the correct mathematical process is executed. For example, here is the code for the multiplication process:

  begin
    if Math = 'Multiply' then
      Answer := FNumber * SNumber;
      Text := FormatFloat('0.#####', Answer);
      Equals.Caption := '= ' + Text;
      NumberEdit.Text := ;
  end;

Just add this statement within the enter button event handler but make sure it is separate from all other if then statements.


The Clear Value Button

Advertisement