2011-05-21 76 views
0

我得到錯誤錯誤:操作員沒有超載在線7.我是否必須做另一個重複,並且不能使用運算符?長度入住帕斯卡爾

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; 
+0

請不要編輯問題的方式,使已發佈的答案不相關。現在你已經創建了一個新的bug。現在,程序不會退出,直到它太長時間纔會停止詢問名稱......您應該按照下面的示例進行操作。 – 2011-05-21 13:27:08

+0

對不起。我已經編輯回原來的代碼。 – orange 2011-05-21 13:28:45

回答

3

首先,你需要寫

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; 
+0

然後while語句中的條件也必須改變。在循環中,長度不能大於10,但while條件允許任何非空的字符串。 – Osiris76 2011-05-21 13:23:03

+0

我明白了,爲什麼括號會有所作爲? 另外我不明白爲什麼在輸出錯誤之後PlayerName需要分配給空白。 任何解釋是非常感謝。 – orange 2011-05-21 13:30:45

+0

@Jeff:如果你寫'PlayerName =''或者Length(PlayerName)> 0,編譯器會嘗試計算'''和'Length(PlayerName)'之間的按位或'',也就是說,你的意思是'PlayerName =(''或Length(PlayerName))> 0'。 – 2011-05-21 13:32:18

0

URM林了類似的情況,

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; 

想知道這是否會工作,程序我把這個不會編譯。