The If Instead of using a bunch of complex nested if statements, you can use a case statement to provide a more readable alternative so long as the conditionals return an integer. A simple numerical case statement
A D V E R T I S E M E N T
var
i : Integer; begin
i :=
RandomRange(15,20);// Generate a random
number from 15 to 20
Case
i of
15 : ShowMessage('Random number was fifteen');
16 : ShowMessage('Random number was sixteen');
17 : ShowMessage('Random number was seventeen');
18 : ShowMessage('Random number was eighteen');
19 : ShowMessage('Random number was nineteen');
20 : ShowMessage('Random number was twenty'); end; end;
Random number was fifteen
The RandomRange routine generates a random number between two given
values. However, each time you run the program, it will always start with the
same pseudo random value (unless you use
RandomSeed)
The case statement above routes the processing to just one of the statements.
OK, the code is a bit silly, but it is used to illustrate the point.
// Set x to 1, 2, 3, then 4 to see what
// message is displayed.
procedure TForm1.Button2Click(Sender: TObject);
var
lbValue: Byte; // Local byte (lb).
begin
lbValue := 3;
case lbValue of
1: ShowMessage('one');
2: ShowMessage('two');
3: ShowMessage('three');
else
ShowMessage('special');
end;
end;
var
i : Integer; begin
i :=
RandomRange(10,20);// Generate a random
number from 10 to 20
Case
i of
15 : ShowMessage('Random number was fifteen');
16 : ShowMessage('Random number was sixteen');
17 : ShowMessage('Random number was seventeen');
18 : ShowMessage('Random number was eighteen');
19 : ShowMessage('Random number was nineteen');
20 : ShowMessage('Random number was twenty'); else
end; end;
Unexpected number : 10
Using enumeration case valuesJust as with
the If statement, the Case statement may use any ordinal type. This
allows us to use the very readable enumeration type:
type
TCar = (Nissan, Ford, Rover, Jaguar);// An
enumeration type var
car : TCar;// An
enumeration variable begin
car := Rover;// Set
this variable
case car of
Nissan : ShowMessage('We have a Nissan car');
Ford : ShowMessage('We have a Ford car');
Rover: ShowMessage('We have a Rover car');
Jaguar : ShowMessage('We have a Jaguar car'); end; end;