HOME - - / - - / - - DELPHI COURSE INDEX - - / - - / - - TUTORIALS INDEX - - / - - / - - Other material for programmers

Delphi Course: First in series using converters to illustrate various points...

This page is information rich, and a has search button at the bottom of the page.

Please don't dismiss it because it isn't full of graphics, scripts, cookies, etc!



You will probably find the text easier to read if you make your browser window much narrower than usual. You may also want to change your browser's zoom level, to enlarge the text. Opera (at least) lets you change zoom level easily. The text will adapt nicely to the settings you decide give the best results for your needs!

The lines of sample Delphi code in these pages will not "wrap". I.e., if a line is too long to show in the width you have set your browser too, parts of the line will be "off the page". Those lines will still copy/paste properly, at least in Opera. Please feel free to send feedback on the choices I've made! (Will you forgive me for not forcing upon you a column of links on the left and a column of ads on the right?)

You may find typos and rough edges in this. None-the-less, the basic information should be accurate. If something seems wrong, or if you find I've assumed knowledge without explaining it in a previous lesson, please let me know. Please forgive matters of typos, etc. for now. I am not inherently sloppy! The blemishes will be dealt with later.




In this lesson, you make an application to convert between feet and meters. The point is in the way the application works... I realise that converting between feet and meters isn't your most pressing need! The lesson, I hope, reinforces previous learning.

You should learn how to...
--- use the OnChange event

You should learn about....
--- What "event driven environment" means
--- Arithmetic within Delphi
--- The concept of "parameters" for functions and procedures

Delphi language:
--- More data types: real, floating point, single

Delphi provided functions:
--- FloatToStringF
--- StrToFloat


This lesson will produce a small program which will convert lengths in inches to lengths in centimeters.

Our initial "solution" will be very similar to the "database" program in the lesson "Very simple data lookup".

Start a new application. Put a button, a label, and an edit box on it. Rename the form conv1f1. Save the unit as conv1u1.pas. Save the project as conv1.dpr

Rename the label laOutput. Make the initial text in the edit box nothing. Rename the button buConvert. Make its caption "&Convert"

As a starting point, make the button's OnClick....
procedure TConv1f1.buConvertClick(Sender: TObject);
var singQuantity:single;
    sTmp:string;
begin
try
singQuantity:=StrToFloat(edit1.text);
laOutput.caption:=FloatToStrF(123.4,ffFixed,7,2);
except
laOutput.caption:='Could not convert';
end;
When you run this, you will be able to enter things into the edit box, but clicking convert will always result in "123.40" appearing in laOutput.caption. That's all right! Always build your applications a little at a time. Believe it or not, it took me about five minutes to get even that much "right". Part of the art of programming is learning to break the development task down into parts, so that you can build your application gradually.

What do we have so far? We have the finished version of the form, populated with all of the controls it will ever have. I.e. what we're seeing on the screen now is what the final customer will see... it just doesn't fully "work" yet.... but that's okay.

We have started the Onclick handler which will make the application "do it".

We have the variables we need. They were declared just after the "var". The variable "sTmp", type string, should hold no terrors... we've made things like it before. The variable singQuantity needs some explanation.

I chose the name singQuantity as follows: The data is of type "single". The first part of the variable name, "sing", reminds me of the variable's type. Delphi won't care... I could call it XQ for all Delphi cares... but the convention is useful. The second part of the name, "Quantity" could have been "Length"... as far as you know so far. As I intend to develop the converter beyond doing mere lengths i wanted to name this variable with a more general noun for "things you can measure".

I'll say more about the "single" data type in a moment. The prefix "sing" joins two you've already seen: "s", for "string" type data and "i" for "integer" type data. I alwyas write the type reminder prefix in lower case, and write the first part of the rest of the name with an uppercase letter.

You (should) already know that sting type variables can hold just about anything, e.g. 'abcde', '123', '2 turtle doves'... but it can't do much with it. You should also remember integer type variables. When you met them, you probably assumed that they were for holding numbers. That's right... up to a point. Integer type variables can only hold whole numbers, e.g. 1, -1, 1234. They can't hold "real" numbers, which is all the integers and numbers with fractional parts, e.g. 12.3, -45.65443.

Even that isn't the whole story... but it will suffice for now!

So... that explains the entries under var.

This application also makes use of the try... except...end structure. Look at the OnClick handler again, find those three words. The application will try to do the things following the word "try". If all goes well, it will ignore from the "except" to its "end". If at any point during the "try" section there's a problem, the application will skip directly to what's in the Except section.

I said "if there's a problem". The problem we are likely to have is an attempt to convert something non-numeric into a number. If, for instance, the user puts "TeddyBear" into the edit box, how is Delphi supposed to turn that into a number?

The Delphi-provided function StrToFloat is what will convert things like the string 456.8 into the number 456.8. "But!," you say, "They are the same!". To you and me... yes. To the computer, no.
sTmp:='456.8';
...would store the string 456.8 in sTmp.
singQuantity:=456.8;
Would store the number 456.8 in singQuantity.

Look at the OnClick handler again. Read the first line from right to left. We start with edit1.caption... the string in the edit box. That is processed by StrToFloat, which changes it into a floating point number, which is a broad term covering type "single" numbers, amoung others. That number is then assigned to the variable singQuantity, i.e., singQuantity "becomes" the number which the string in edit1.caption represented.

Moving on to the next line....

The caption of laOutput will become a string. That string will derive from the number 123.4. FloatToStrF is always followed by four things (called "parameters") in one set of brackets. The first is the floating point number to be converted to a string, the second is a code for how the number should be written, the third and fourth have various meanings, depending on what the second paramter was. In the case of ffFixed, the thrid parameter should be a 7 for single type data, and the fourth determines how many places are given to the right of the decimal point. Run the application with the fourth number 1, and you'll get 123.4; run it with the fourth number 3 and you'll get 123.400.

Got that? Got indigestion? Hang in there. Time to make the program work better. Make the try... except section be...
try
singQuantity:=StrToFloat(edit1.text);
laOutput.caption:=FloatToStrF(singQuantity,ffFixed,7,2);
except
That should make your application "work" a little better... whatever you enter into the edit box, provided it looks like a number, should be coming out in laOutput when you click buConvert.

(A little aside: Notice I name components a bit like I name variables? Lables all have names beginning with la, buttons with bu. If I wanted to re-name the edit box, I'd call it eInput. End of aside!)

A little mathematics for you: To convert inches to meters, you need to divide the inches number by 39.37. 39.37 inches is one meter. To convert inches to centimeters, you divide by 0.3937

To make the computer do this for us, we need merely to add one line....
try
singQuantity:=StrToFloat(edit1.text);
singQuantity:=singQuantity/0.3937;  //new line
laOutput.caption:=FloatToStrF(singQuantity,ffFixed,7,2);
except
If that looks strange to you, you are reading ":=" as equals, aren't you? The new line actually says:"What's in singQuantity becomes what was in singQuantity previously, divided by 0.3937.

Congratulations! The converter is working! Your mother would say "That's very nice, dear." You father would say "But it's not working very well... why do I have to keep clicking that wretched 'Convert' button?"

Take a braek. When we come back, will eliminate that annoyance.


The secret to getting rid of the 'Convert' button is to tap into another of the events Windows provides and watches for. There's an OnChange event for the edit box. As it is the event you most often want to use, simply double clicking on the edit box will bring up the following OnChange handler starting point in the code editor...
procedure TConv1f1.Edit1Change(Sender: TObject);
begin

end;
(The Object Inspector will show you that there are 14 other events which arise from any edit box. Aren't you glad we don't have to think about them for a while?)

Put...
// of Edit1Change
... after the "end" shown above. Delete the "begin" just above that "end".

Copy what's in your buConvert OnCLick handler, between (exclusive) it's "preocedure..." line and the final "end", and paste it into the Edit1Change section of your code. Be careful not to add or remove "ends".

In a moment you are going to try running the application again. When you do: DON'T, for now, type anything into the edit box that isn't a digit, i.e. 0,1,2,3...8,9. You can use the delete key, but DON't, for now, delete everything in the box. Always leave at least one digit. Program working without using the "Convert" button? It should be!

Quit the application, bring up the form, click on the "Convert" button, press your delete key... the button should disappear. Re-save your project. Re-run it, again putting only numbers into the edit box. It should still work, as long as you only enter numbers. Quit the application again, and look through the code. You will still find...
procedure TConv1f1.buConvertClick(Sender: TObject);
var sTmp:string;...
... even though there's no longer a Convert button to click!

This does no harm, other than wasting space and introducing something which might confuse you when looking at your code later. Always do what you can to eliminate opportunities for confusion! In this case, we will remove the redundant OnClick Handler.

Don't remove it the obvious way. That will leave troublesome loose ends.

Think back to the creation of the event handler. You double clicked on the button, and Delphi created the skeleton of the handler. Some parts of that skeleton were not obvious at the time. I didn't explain them, because they are not important to you yet. However, they are there, and need to be respected.

If you look at the early parts of Conv1U1, you'll see...

It starts with the word "unit"
A little farther down, you'll see "uses".
A little farther down, you'll see "type".

Within that section, you'll see "procedure buConvertClick(Sender: TObject);". Don't do anything to it. Delphi will deal with this part of the code for you.

Go down to where you have....
procedure TConv1f1.buConvertClick(Sender: TObject);
var sTmp:string;
    singQuantity:single;
begin
try
singQuantity:=StrToFloat(edit1.text);
singQuantity:=singQuantity/0.3937;
laOutput.caption:=FloatToStrF(singQuantity,ffFixed,7,2);
except
laOutput.caption:='Could not convert';
end;

end;
Make that just

procedure TConv1f1.buConvertClick(Sender: TObject);
begin
end;
... in other words take "the heart" out of the definition of buConvertClick. Be careful to leave in the "begin". Be careful to take out enough "end"s, without taking out too many. There should be just one left before

procedure TConv1f1.Edit1Change(Sender: TObject);
.. or whatever you have after duConvertClick.

Now re-save the project. The....

procedure TConv1f1.buConvertClick(Sender: TObject);
begin
end;
... "magically" disappears, along with the reference in the type clause at the top of the program. Be sure it still runs okay! Delphi does a good job of managing things, and you should rely on it.

A little way back, I said you should run the application, but that you should not enter anything non-numeric. In a moment, I want you to run it and put in something non-numeric, but first you should understand what you are going to see. As soon as you enter something non-numberic, the StrToFloat in the Onchange handler is going to have a problem. When it has that problem, Delphi will stop your program and put an error message on the screen. You can click the "OK" on the error message, and then you need to re-run the program. (Either click the green right-pointing arrow in the Speedbar, or press F9, or use the menu item Run, and the subordinate Run).

Youo are seeing the error message, and having to restart the application because you ran it from within Delphi. To see what a customer would experience, save your project, then select Delphi's File | Close All. (Delphi will still be running, but no project will be activee.)

Use Windows Explorer or similar to go to the exe file that Delphi created. Run that. Now the program "works" without interruption. When you enter non-numerics, the try... except...end structure does it's job (you can see the "Could not convert") message cropping up)... but, because Delphi is not supervising the execution of the program, you don't get the error messages. Ta! Da!


Have a look at the "In this lesson...." material at the top of the page. Be sure you're clear on the various points.




Click here if you're feeling kind! (Promotes my site via "Top100Borland")
   Search this site or the web        powered by FreeFind
 
  Site search Web search
Site Map    What's New    Search
Ad from page's editor: Yes.. I do enjoy compiling these things for you... I hope they are helpful. However.. this doesn't pay my bills!!! If you find this stuff useful, (and you run an MS-DOS or Windows PC) please visit my freeware and shareware page, download something, and circulate it for me? Links on your page to this page would also be appreciated!
Click here to visit editor's Sheepdog Software (tm) freeware, shareware page.

Link to Tutorials main page Link to Delphi Course index
Here is how you can contact this page's author, Tom Boyd.


Valid HTML 4.01 Transitional Page tested for compliance with INDUSTRY (not MS-only) standards, using the free, publicly accessible validator at validator.w3.org


If this page causes a script to run, why? Because of things like Google panels, and the code for the search button. Why do I mention scripts? Be sure you know all you need to about spyware.

....... P a g e . . . E n d s .....