I get the error Error: Operator is not overloaded on line 7. Do I have to do a another repeat and can't use the and operator?
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;
First, you need to write
If (PlayerName = '') And (Length(PlayerName) > 10) Then
The parentheses are required.
Secondly, this will always evaluate to false
, because there is no string that is both empty and has length 11 or more. Indeed, a string is empty if and only if its length is zero, so basically you say "if the length is zero and the length is 11 or more, then...".
Most likely you wish instead to use a disjunction, that is, to use or
instead of and
:
If (PlayerName = '') Or (Length(PlayerName) > 10) Then
This will display the error message if the name is empty or if it is too long.
In addition, the loop will exit even if the name is invalid, because if PlayerName
is equal to ThisIsATooLongName
then indeed PlayerName <> ''
.
What you need is something like
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;
or
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;