0
Function GetPlayersName: String;
Var
  PlayerName: String;
  i: Integer;
Begin
  Write('What is your name? ');
  Readln(PlayerName);

  for i := 1 to length(PlayerName) do
  begin
    PlayerName[i] := Upcase(PlayerName[i]);
    if not(PlayerName[i] in ['A' .. 'Z']) AND (PlayerName[i] <> ' ') then
    begin
      writeln('Letters and spaces please');
    end;
  end
else
  GetPlayersName := PlayerName;
end;

For some reason, during the above validation, the else statement won't compile. Here is the error message:

[dcc32 Error] AQA_Reverse.dpr(125): E2029 'END' expected but 'ELSE' found

As well as this, when the message is printed, it prints by the number of characters and I don't know how to change it.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Deadraa
  • 11
  • 1
  • 5

2 Answers2

2

The error message is because your else is not associated with any if statement. And you are not breaking your loop when you encounter an unacceptable character.

Your entire function should be rewritten. Try something more like this instead:

Function GetPlayersName: String;
Var
  PlayerName: String;
  i: Integer;
Begin
  Repeat
    Write('What is your name? ');
    Readln(PlayerName);
    PlayerName := Trim(PlayerName);

    for i := 1 to Length(PlayerName) do
    begin
      if not (PlayerName[i] in ['A' .. 'Z', 'a'..'z', ' ']) then
      begin
        Writeln('Letters and spaces please');
        PlayerName := '';
        Break;
      end;
    end;
  Until PlayerName <> '';
  GetPlayersName := PlayerName;
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

You seem to be confusing Delphi with Python. Python's for loops may have else clauses, which are executed if you don't exit the loop early. Delphi doesn't have that feature.

There are ways to emulate that behavior by using some additional variables and logic, but I don't think that's what you really need anyway.

Validation of the string contents isn't the problem, if you meant to detect 26 different letters and spaces. (There are more than 26 letters, but I assume you're not interested in that.) Your code correctly detects not-letter, non-space characters and reports about them.

You need to reconsider how your function is supposed to work when it detects an error. Right now, the function prints an error message (forevery invalid character), but then what should the return value be? You don't assign a result in that case. Maybe you intend for the function to re-prompt for the name until the user enters a valid value. If that's what you want, then of course you'll need to include a call to ReadLn inside a loop; your current code clearly only reads input once.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467