您的位置:首页 > 编程语言 > Delphi

Delphi学习笔记四——语句

2016-05-23 08:32 501 查看
今天我们来看一下Delphi的语句。

一、常量声明语句

和其他语言一样,常量在声明时就被赋值,且在程序执行过程中是不可改变的。常量用“=”表示两边的值是相等的。

[delphi] view
plaincopy

const

Pi = 3.14159;

Answer = 342;

ProductName = 'Delphi';

二、赋值语句

这个语句最常用,在之前也介绍过。这里就举个例子。

[delphi] view
plaincopy

variable := expression;

扩展方法{X+}:MyFunction(X)。这种方法被调用时,其返回值将会被丢弃。

三、goto语句

goto语句可以用来从程序中的一个地方直接跳转到另一个地方,但不常用。

四、复合语句

首尾使用begin和end包括起来的一组语句,可以嵌套使用,也允许空的复合语句。

[delphi] view
plaincopy

begin

c:=a;

a:=b;

b:=c;

begin

...

end;

end;

五、if语句

这个在日常的程序开发中也是经常用到。在之前的博文中也有介绍。这里不做详述,如有使用其他语言的经验,只需要注意Delphi对于if的语法即可。

[delphi] view
plaincopy

if A then B

if A then B else C

举例来说:

[delphi] view
plaincopy

if J <> 0 then

begin

Result := I/J;

Count := Count + 1;

end

else if Count = Last then

Done := True

else

Exit;

六、case语句

case语句用来在多个可能的情况下选择一个条件。例如

[delphi] view
plaincopy

case MyColor of

Red: X := 1;

Green: X := 2;

Blue: X := 3;

Yellow, Orange, Black: X := 0;

end;

case Selection of

Done: Form1.Close;

Compute: CalculateTotal(UnitCost, Quantity);

else

Beep;

end;

七、repeat语句

repeat语句重复执行一行或一段语句直到某一状态为真。例如

[delphi] view
plaincopy

repeat

K := I mod J;

I := J;

J := K;

until J = 0;

repeat

Write('Enter a value (0..9): ');

Readln(I);

until (I >= 0) and (I <= 9);

这里需要说明的是,repeat至少执行一次语句

八、while语句

while语句与repeat语句的不同之处在于while语句在循环的开始阶段就进行判断,也就不存在多执行一次循环语句的情况了。

[delphi] view
plaincopy

while Data[I] <> X do I := I + 1;

while I > 0 do

begin

if Odd(I) then Z := Z * X;

I := I div 2;

X := Sqr(X);

end;

while not Eof(InputFile) do

begin

Readln(InputFile, Line);

Process(Line);

end;

九、for语句

for语句需要明确指定想要的循环来遍历的迭代次数:

[delphi] view
plaincopy

<p>for I := 2 to 63 do

if Data[I] > Max then

Max := Data[I];

for I := ListBox1.Items.Count - 1 downto 0 do

ListBox1.Items[I] := UpperCase(ListBox1.Items[I]);

for I := 1 to 10 do

for J := 1 to 10 do

begin

X := 0;

for K := 1 to 10 do

X := X + Mat1[I, K] * Mat2[K, J];

Mat[I, J] := X;

end;</p><p>for C := Red to Blue do Check(C);</p>

十、Break过程

调用Break()表示当循环中满足某种条件时立即跳出循环。例如

[delphi] view
plaincopy

var

i:integer;

begin

for i:=1 to 100 do

begin

if i=30 then break;

end;

end;

十一、Continue()过程

调用Continue()重新开始下次循环。例如

[delphi] view
plaincopy

var

i : integer;

begin

for i:=1 to 3 do

begin

writeln(i,'before continue');

if i=2 then continue;

writeln(i,'after continue');

end;

end;

十二、with()语句

在使用记录类型的时候,使用with语句来针对某一个变量说明。with语句的结构为

[delphi] view
plaincopy

with obj do statement or with obj1,obj2,...,objn do statement

with语句的例子

[delphi] view
plaincopy

with OrderDate do

if Month = 12 then

begin

Month := 1;

Year := Year + 1;

end

else

Month := Month + 1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: