【问题标题】:delphi pick a random value from an enumdelphi 从枚举中选择一个随机值
【发布时间】:2013-10-20 02:51:49
【问题描述】:

我需要在 java JAVA CODE 中为这个解决方案提供一个 delphi 解决方案

type
 TColors = (red, green, blue, white, purple, orange, yellow, black);
type
 TForm1 = class(TForm)
 Button1: TButton;
 Memo1: TMemo;
 procedure Button1Click(Sender: TObject);
 private
 { Private-Deklarationen }
 public
 { Public-Deklarationen }
 end;

 var Form1: TForm1;

 implementation

 {$R *.fmx}

 function RandomColor: TColors;
 begin
  result := blue;  //   make this random value from enum ????
end;

procedure TForm1.Button1Click(Sender: TObject);
var
s: string;
begin
  s := GetEnumName(TypeInfo(TColors), integer(RandomColor));
 Memo1.Lines.Add(s);   ///  print random color to memo 
end;

【问题讨论】:

    标签: delphi


    【解决方案1】:

    这是一个完整的测试程序,包括检查 Low(TColors) 不为零,如果以后由于某种原因发生更改,则必须在 RandomColor 函数中将其考虑在内。

    program Project7;
    
    {$APPTYPE CONSOLE}
    {$RANGECHECKS ON}
    
    uses
      SysUtils;
    
    type
      TColors = (red, green, blue);
    
    const NAMES : array[TColors] of string = ('red','green','blue');
    
    function RandomColor: TColors;
    begin
      ASSERT( Ord(Low(TColors)) = 0);
      Result := TColors(Random(1+Ord(High(TColors))));
    end;
    
    var i : integer;
    begin
      Randomize; 
      while true do begin
        for i := 0 to 7 do write('"', NAMES[RandomColor], '" ');
        writeln;
        writeln('press Ctrl+C to break, ENTER to continue ');
        readln;
      end;
    end.
    

    【讨论】:

      【解决方案2】:
      function RandomColor: TColors;
      begin
        Result := TColors(Random(Succ(Ord(High(TColors)))));
      end;
      
      var
        MyColor: TColors;
      begin
        Randomize; //call this once at startup
        MyColor := RandomColor;
      

      【讨论】:

      • 我会在 Ord() 中添加 +1,否则您将永远不会看到可能的最高枚举值。上限是排他性的。
      • 好像有错误。 Random(A) 返回 0..A-1 的范围,所以如果你想包含最后一个元素,你需要使用 Random(A+1)
      • @JensG 和 Krom - 完全正确,谢谢 - 我现在添加了 Succ 调用。
      • 在我的 Delphi XE 上使用 Succ() 和 RANGECHECKS 甚至无法编译它。不错的解决方案,确实。顺便说一句,为什么在我们纠正你的东西的时候你能赚到所有的分数?
      • @JensG - Succ 调用是针对整数的,因此在启用范围检查的情况下工作正常 - 我不知道为什么你的 Delphi XE '甚至不编译这个'。也许您没有正确复制和粘贴?
      猜你喜欢
      • 1970-01-01
      • 2018-07-07
      • 2020-09-10
      • 2016-05-18
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      相关资源
      最近更新 更多