2011-05-21 78 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; 

想知道这是否会工作,程序我把这个不会编译。