《Delphi 7编程技巧与实例精解》实例3
看了题目之后我先按自己的思路实现了,我是在点击“显示”按键的时候再一次性检查控件的属性,来确定ShowMessage的内容。
书本给出的程序样例是在每次用户点击控件的时候就更新一次存有message内容的变量,我想这样应该比较浪费资源吧,不过程序很小,估计没影响。
姓名、性别、学习成绩这些都相对简单。兴趣爱好那里,建立一个flag变量来确定是否有选择。感觉写了好多行把flag设置为True的代码,不知道VCL本身有没有更简单的函数来提供这个检验。
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Button1: TButton;
Edit1: TEdit;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
RadioGroup1: TRadioGroup;
GroupBox1: TGroupBox;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
CheckBox4: TCheckBox;
CheckBox5: TCheckBox;
CheckBox6: TCheckBox;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
name,gender,grade,hobbies: String;
hobbyList: Array of String;
procedure TForm1.Button1Click(Sender: TObject);
var
msg,hobby: String;
hobbiesFlag: Boolean;
begin
//clear
name := '';
gender := '';
grade := '';
hobbies := '';
hobbiesFlag := False;
setLength(hobbyList,6);
hobbyList[0] :='文学';
hobbyList[1] :='音乐';
hobbyList[2] :='棋牌';
hobbyList[3] :='绘画';
hobbyList[4] :='体育';
hobbyList[5] :='数学';
//set name
name := Edit1.Text;
//set gender
if RadioButton1 .Checked then
gender := '男';
if RadioButton2.Checked then
gender := '女';
//set grade
if RadioGroup1.ItemIndex > -1 then
case RadioGroup1.ItemIndex of
0: grade := '优';
1: grade := '良';
2: grade := '中';
3: grade := '差';
end;
//set hobbies
if CheckBox1.Checked then
begin
hobbiesFlag := True;
hobby := hobby + hobbyList[0] + '、';
end;
if CheckBox2.Checked then
begin
hobbiesFlag := True;
hobby := hobby + hobbyList[1] + '、';
end;
if CheckBox3.Checked then
begin
hobbiesFlag := True;
hobby := hobby + hobbyList[2] + '、';
end;
if CheckBox4.Checked then
begin
hobbiesFlag := True;
hobby := hobby + hobbyList[3] + '、';
end;
if CheckBox5.Checked then
begin
hobbiesFlag := True;
hobby := hobby + hobbyList[4] + '、';
end;
if CheckBox6.Checked then
begin
hobbiesFlag := True;
hobby := hobby + hobbyList[5] + '、';
end;
//show message
if name = '' then
showMessage('请输入名字')
else if gender = '' then
showMessage('请输入性别')
else if grade = '' then
showMessage('请输入成绩')
else if hobbiesFlag = False then
showMessage('请选择爱好')
else
begin
msg := '您的姓名是:'+name+ #13#10 +
'您的性别是:'+gender+ #13#10 +
'您的学习成绩是:'+grade+ #13#10 +
'您的爱好是:' + hobby;
msg[msg.Length] := #13;
msg := msg + #10;
ShowMessage(msg);
end;
end;
end.
运行结果: