Search code examples
delphiwhile-loopdelphi-2010

Delphi 2010 while loop


I have a problem with a While Loop.

I need the TotalCost to be displayed in SpreeWin and the Shopping sprees to be shown as below

Your spending limit that you have won is R 890

On spree #1 you may spend R100

On spree #2 you may spend R340

On spree #3 you may spend R450

  ListHead := 'Max per spree is R500.00 Max limit is R10000.00';
  lstLimit.Items.Add(ListHead);

  Count := random(20) + 1;
  MaxCost := random(10000) + 1;
  TotalCost := 0;


  SpreeWon := 'Your spending limit that you have won is  R' + IntToStr(TotalCost);
  lstLimit.Items.Add(SpreeWon);


  while TotalCost <= MaxCost do
    begin
         Prize := Random(500) + 1;
         TotalCost := TotalCost + Prize;
         ListItems := 'On spree # ' + IntToStr(Count) + ' you may spend R' + IntToStr(Prize);
         lstLimit.Items.Add(ListItems);
    end;

 Cost := 'Total prize value : R' + IntToStr(TotalCost);
 lstLimit.Items.Add(Cost);

Solution

  • You're adding the item for total cost while TotalCost is 0, insert it when you've got it. For the spree count, well you should count it:

      var
        SpreeCount: Integer;
        ..
    
    
      ..
      TotalCost := 0;
    
      // comment the below
      // SpreeWon := 'Your spending limit that you have won is  R' + IntToStr(TotalCost);
      // lstLimit.Items.Add(SpreeWon);
    
      SpreeCount := 0; // <--
    
      while TotalCost <= MaxCost do
        begin
             Prize := Random(500) + 1;
             TotalCost := TotalCost + Prize;
    
             Inc(SpreeCount); // <--
             // substitute SpreeCount for Count in the below
             ListItems := 'On spree # ' + IntToStr(SpreeCount) + ' you may spend R' + IntToStr(Prize);
             lstLimit.Items.Add(ListItems);
        end;
    
     Cost := 'Total prize value : R' + IntToStr(TotalCost);
     lstLimit.Items.Add(Cost); 
    
      // insert SpreeWon
      SpreeWon := 'Your spending limit that you have won is  R' + IntToStr(TotalCost); // <--
      lstLimit.Items.Insert(0, SpreeWon); // <--