首先,你需要寫
If (PlayerName = '') And (Length(PlayerName) > 10) Then
括號是必需的。
其次,這將總是評估爲false
,因爲沒有字符串都是空的,長度爲11或更多。事實上,一個字符串是空的,當且僅當它的長度爲零時,基本上你會說「如果長度爲零,長度爲11或更大,則...」。
最有可能你想,而不是使用脫節,也就是使用or
而不是and
:
If (PlayerName = '') Or (Length(PlayerName) > 10) Then
如果名稱爲空或這將顯示錯誤消息,如果太長。
另外,即使名稱無效,循環也會退出,因爲如果PlayerName
等於ThisIsATooLongName
那麼的確是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;
請不要編輯問題的方式,使已發佈的答案不相關。現在你已經創建了一個新的bug。現在,程序不會退出,直到它太長時間纔會停止詢問名稱......您應該按照下面的示例進行操作。 – 2011-05-21 13:27:08
對不起。我已經編輯回原來的代碼。 – orange 2011-05-21 13:28:45