6. Making decisions

To make decisions, a program has to determine wether a condition is TRUE or FALSE.
This is done in a conditional statement, where the program flow splits up in two "branches".

In this lesson, we'll talk about the IF statement.

The conditional statement  IF - THEN - ELSE

What is the first decision to be made in procedure ShowFromFootOrMeter?

Such a decision is made with an if-then-else statement:

if a_condition then statement else another_statement;

Instead of following the word then by a single statement, you may also follow it by a block of statements, nested between the words begin and end. The same goes for the else part.

Important: no semicolon is allowed immediately before an else !

Taking into account that the first radiobutton is button number 0

if RadioGroup.ItemIndex = 0 then 
Using if... then... else... will improve your code, making it more readable and even a bit faster.

Let's code!

  1. Rewrite procedure ShowFromFootOrMeter as follows:
    if RadioGroup1.ItemIndex = 0 then begin 
    // Show the components for inches
    lblInput2.Visible := True;
    edInput2.Visible := True;
    edInput1.Text := '';
    edInput2.Text := '';
    // Show the names of the starting length units
    lblInput1.Caption := 'foot';
    lblInput2.Caption := 'inch';
    else begin
    // Hide the components for inches
    lblInput2.Visible := False;
    edInput2.Visible := False;
    edInput1.Text := '';
    // Show the name of the starting length unit
    lblInput1.Caption := 'meter';
  2. Rewrite procedure btnConvertClick as follows:
    if RadioGroup1.ItemIndex = 0 then begin
    Foot := StrToFloat(edInput1.Text);
    Inch := StrToFloat(edInput2.Text);
    // Convert Foot + Inch to meter
    Meter := (Foot * 0.3048) + (Inch * 0.3048 / 12);
    // Show the string in the CAPTION of lblResult
    ResultMeter := FormatFloat('0.00', Meter);
    lblResult.Caption := ResultMeter + ' meter';
    else begin
    Meter := StrToFloat(edInput1.Text);
    // Convert from meter to foot
    Foot := Meter / 0.3048;
    // Convert from foot to foot and inch
    FootInteger := Trunc(Foot);  // remove the part after the decimal separator
    Inch := (Foot - FootInteger) * 12; // convert the rest to inch
    // Show the result in the CAPTION of lblResult
    ResultFoot := FormatFloat('0', FootInteger);
    ResultInch := FormatFloat('0', Inch);
    LblResult.Caption := ResultFoot + ' foot ' + ResultInch + ' inch';
  3. Compile your program and test it thoroughly.

  4. Finally, we'll add the finishing touch to this version of Foot2MRadio. We'll change the vertical layout of the radiogroup to horizontal.

    Select RadioGroup1. In the Object Inspector, change the property Columns from 1 to 2. Now it should look like this: