开发者

How to add up the integer values in a label in delphi

I am currently having problems with screating a scoreboard in Delphi.

I have a series of forms which are individual questions. If the questions are answered correctly, then the score is 1. Otherwise the score is -开发者_如何转开发1.

On my scoreboard at the moment, I have 12 labels and 11 of them contain the score for each of the forms. What I would like to do is add up the numbers in each of the labels and output the final score into the 12th label.

Is there a way of doing this? Any help will be greatly appreciated.


You should use the UI purely for displaying your values.

For working with your data you should use appropriate data structures: array, lists, etc.

Example using an Array:

var
  Scores[0..10]: Integer;
  Sum: Integer;

procedure CollectData;
var
  i: Integer;
begin
   Scores[0] := ...;
   //...
   Scores[10] := ...;

   Sum := 0;
   for i := Low(Scores) to High(Scores) do
     Sum := Sum + Scores[i];
end;

procedure DisplayData;
begin
  Label1.Caption := IntToStr(Scores[0]);
  //...
  Label11.Caption := IntToStr(Scores[10]);
  Label12.Caption := IntToStr(Sum);
end;


  1. Neat solution: Keep scores as integers in Integer fields
  2. Not so neat solution:

    SumLabel.Caption := IntToStr( StrToIntDef( Label1.Caption, 0 ) + StrToIntDef( Label2.Caption, 0 ) + ... );


Although I think @DR's answer is spot-on, and @Ritsaert's is helpful, here's another option.

Your label components will have a 'TAG' property - you can use this for your own purposes and in your case I'd just set the TAG property at the same time as you set the Caption.

The advantage behind this is that you can format your caption to contain more than a simple number (if you wish), and also you are just summing up tags (which are already integers and don't need you to do the extra work behind a StrToIntDef call). Really, you're following @DR's point about keeping values out of the GUI (in a sense), you're using a storage field in each label instead.

eg;

when setting a score;-

Label1.Caption:=Format('%d point',[FScore]);
Label1.Tag:=FScore;

and when summing them;-

FSum:=Label1.Tag + Label2.Tag + Label3.Tag (etc)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜