0

我收到错误错误:第 7 行的运算符未重载。我是否必须再次重复并且不能使用and运算符?

Function GetValidPlayerName : String;
  Var
    PlayerName : String;
  Begin
    Repeat
      Readln(PlayerName);
      If PlayerName = '' And Length(PlayerName) > 10
        Then Write('That was not a valid name.  Please try again: ');
    Until PlayerName <> '';
    GetValidPlayerName := PlayerName;
  End;
4

2 回答 2

3

首先,你需要写

If (PlayerName = '') And (Length(PlayerName) > 10) Then

括号是必需的。

其次,这将始终评估为false,因为不存在既为空又长度为 11 或更长的字符串。事实上,一个字符串当且仅当它的长度为零时才为空,所以基本上你说“如果长度为零并且长度为 11 或更多,那么......”。

您很可能希望改为使用析取,即使用or而不是and

If (PlayerName = '') Or (Length(PlayerName) > 10) Then

如果名称为空或太长,这将显示错误消息。

此外,即使名称无效,循环也会退出,因为 if确实PlayerName等于ThisIsATooLongNamethen PlayerName <> ''

你需要的是类似

Function GetValidPlayerName : String;
Var
  PlayerName : String;
Begin
  Repeat
    Readln(PlayerName);
    If (PlayerName = '') Or (Length(PlayerName) > 10) Then
    Begin
      Write('That was not a valid name.  Please try again: ');
      PlayerName := '';
    End;
  Until PlayerName <> '';
  GetValidPlayerName := PlayerName;
End;

或者

Function GetValidPlayerName : String;
Var
  PlayerName : String;
Begin
  result := '';
  Repeat
    Readln(PlayerName);
    If (PlayerName = '') Or (Length(PlayerName) > 10) Then
      Write('That was not a valid name.  Please try again: ')
    Else
      result := PlayerName;
  Until result <> '';
End;
于 2011-05-21T13:17:39.483 回答
0

Urm 我也有类似的情况,

while(Length(conversionrates[i].rate)<>2)) do
begin
    writeln('the conversion name should be 2 letters. (E.G Pounds to Dollars would be "PD")');
    readln(conversionrates[i].fromto);
end;

想知道这是否可行,我放置的程序无法编译。

于 2015-03-31T10:08:28.367 回答