Frage

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;
War es hilfreich?

Lösung

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;

Andere Tipps

Urm Im in a similar situation,

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;

Wondering if this would work, the program I put this is wont compile.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top