I'm new to Lazarus and today I faced an issue with if-else usage. Everything is ok while there is only an if statement but when I'm trying to write an if-else statement this error shows up:
unit1.pas(48, 3) Fatal: Syntax error, ";" expected but "Else" found
I'm not sure if I need to wrap code inside the statements with begin end
, but this FreePascal wiki page shows it like this
My code:
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Math;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
a, b, c, d, x, x1, x2:real;
begin
a := strToFloat(Edit1.Text);
b := strToFloat(Edit2.Text);
c := strToFloat(Edit3.Text);
d := Power(b, 2) - 4 * a * c;
if d > 0 then
x1 := (-b + sqrt(d))/(2 * a);
x2 := (-b - sqrt(d))/(2 * a);
Label1.Caption := 'x1 = ' + floatToStr(x1) + #10 + 'x2 = ' + floaTToStr(x2)
else
if d < 0 then
Label1.Caption := 'Розв*язків немає';
else
x1 := (-b + sqrt(d))/(2 * a);
Label1.Caption := 'x = ' + floatToStr(x);
end.
You seem to be trying to use indentation to group code under statements. Pascal doesn't use indentation for nesting code (I'm honestly unsure what its called). You need to use begin
and then afterwards end
.
Meaning you code should look as follows:
if d > 0 then
begin
// All 3 lines below will run if "d > 0"
x1 := (-b + sqrt(d)) / (2 * a);
x2 := (-b - sqrt(d)) / (2 * a);
Label1.Caption := 'x1 = ' + floatToStr(x1) + #10 + 'x2 = ' + floatToStr(x2);
end // Do not ";" since the if statement is not over yet
else if d < 0 then
begin
Label1.Caption := 'Розв*язків немає';
end // Do not ";" since the if statement is not over yet
else
begin
x1 := (-b + sqrt(d)) / (2 * a);
Label1.Caption := 'x = ' + floatToStr(x);
end; // End of the if statment