首先,你需要写
If (PlayerName = '') And (Length(PlayerName) > 10) Then
括号是必需的。
其次,这将始终评估为false
,因为不存在既为空又长度为 11 或更长的字符串。事实上,一个字符串当且仅当它的长度为零时才为空,所以基本上你说“如果长度为零并且长度为 11 或更多,那么......”。
您很可能希望改为使用析取,即使用or
而不是and
:
If (PlayerName = '') Or (Length(PlayerName) > 10) Then
如果名称为空或太长,这将显示错误消息。
此外,即使名称无效,循环也会退出,因为 if确实PlayerName
等于ThisIsATooLongName
then 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;