我的 if 语句有什么问题?

What is wrong with my if-statement?

我现在正在尝试探索 Pascal。我 运行 进入了一些编译器错误。我写了一个 if else if 语句,如下所示:

  if ((input = 'y') or (input = 'Y')) then
    begin
      writeln ('blah blah');
    end;
  else if ((input = 'n') or (input = 'N')) then
    begin
      writeln ('blah');
    end;
  else
    begin
      writeln ('Input invalid!');
    end;

它在第一个 else:

给我一个错误

";" expected but "ELSE" found

我找了很多关于 if 语句的教程,他们就像我一样:

if(boolean_expression 1)then 
   S1 (* Executes when the boolean expression 1 is true *)

else if( boolean_expression 2) then 
   S2 (* Executes when the boolean expression 2 is true *)

else if( boolean_expression 3) then 
   S3 (* Executes when the boolean expression 3 is true *)

else 
   S4; ( * executes when the none of the above condition is true *)

我试图删除 beginend 但出现了同样的错误。这是编译器错误吗?

P.S。我在案例陈述中这样做。不过我觉得不重要。

在大多数情况下,

; 不允许出现在 else 之前。

  if ((input = 'y') or (input = 'Y')) then
    begin
      writeln ('blah blah');
    end
  else if ((input = 'n') or (input = 'N')) then
    begin
      writeln ('blah');
    end
  else
    begin
      writeln ('Input invalid!');
    end;

将编译。 但是...更喜欢使用 begin ... end 括号以避免在复杂的 if then else 语句中误解代码。 像这样会更好:

  if ((input = 'y') or (input = 'Y')) then
  begin
    writeln('blah blah');
  end
  else
  begin
    if ((input = 'n') or (input = 'N')) then
    begin
      writeln('blah');
    end
    else
    begin
      writeln('Input invalid!');
    end;
  end;

第二个示例更容易阅读和理解,不是吗?

当您删除 beginend 时代码不起作用,因为 else 之前有一个分号。这将编译没有错误:

  if ((input = 'y') or (input = 'Y')) then
    writeln('blah blah')
  else
  begin

  end;

附加 @lurker

的评论

请看下面没有 begin ... end 方括号的例子。

  if expr1 then
    DoSmth1
  else if expr2 then
    if expr3 then
      DoSmth2
    else
     DoSmth3;//Under what conditions is it called?

这里看不清楚,如果DoSmth3是在not (expr2)(expr2) and (not (expr3))上调用的。虽然我们可以预测此示例中的编译器行为,但是没有 begin ... end 的更复杂的代码容易出错并且难以阅读。见以下代码:

  //behaviour 1
  if expr1 then
    DoSmth
  else if expr2 then
  begin
    if expr3 then
      DoSmth
  end
  else
    DoSmth;

  //behaviour 2
  if expr1 then
    DoSmth
  else if expr2 then
  begin
    if expr3 then
      DoSmth
    else
      DoSmth;
  end;

现在代码行为很明显了。