Variables, program loopIf we want our console application to run for some time, instead of terminating after outputting a few lines,
we have to set up a program loop. program ConsoleTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
Quit: Boolean;
S: string;
begin
try
WriteLn('To quit, press Q followed by ENTER');
Quit := False;
while not Quit do begin
ReadLn(S);
Quit := (S = 'q') OR (S = 'Q');
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
In a GUI application (Windows program), we don't have to set up such a "program loop". But an archaic console application is not a "real time" application, it is not "event driven" by events, such as mouse clicks and keyboard presses. Just as in the old days, you as the programmer have to instruct the program to wait for key presses, examine which keys were pressed, and make the program act accordingly. Let's make the program actually do something. We assume that the code speaks for itself: program ConsoleTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
Quit: Boolean;
S: string;
R, Guess: integer;
begin
try
Randomize;
R := Random(10);
WriteLn('Guess a number');
WriteLn('To stop, press Q followed by ENTER');
Quit := False;
while not Quit do begin
ReadLn(S);
Quit := (S = 'q') OR (S = 'Q');
if not Quit then begin
if S[1] in ['0'..'9'] then begin
Guess := StrToInt(S);
if Guess = R then begin
WriteLn('Correct! Press ENTER to quit');
ReadLn;
Quit := True;
end
else if Guess < R then
WriteLn('Wrong... try higher:')
else
WriteLn('Wrong... try lower:')
end
else
WriteLn('Try again...');
end;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
« Part 1: Setting up and Compiling a Console
Application |
|
© Copyright 1999-2022
DelphiLand