delphi从枚举中选择一个随机值

时间:2013-10-11 22:12:27

标签: delphi

我需要在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;

2 个答案:

答案 0 :(得分:5)

function RandomColor: TColors;
begin
  Result := TColors(Random(Succ(Ord(High(TColors)))));
end;

var
  MyColor: TColors;
begin
  Randomize; //call this once at startup
  MyColor := RandomColor;

答案 1 :(得分:0)

这是一个完整的测试程序,包括对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.