Home > Blockchain >  Condition always evaluates to true regardless of actual values
Condition always evaluates to true regardless of actual values

Time:11-06

I have created an if statement that I want to output a message using the `ShowMessage() function when an entered code matches a generated code. However, it still outputs the "well done!" message even when blatantly wrong.

Button code:

procedure TfrmCAPTCHA.btnCheckClick(Sender: TObject);
var
  sCode, sAnswer : string;
  bRightAnswer, bWrongAnswer : boolean;
begin

  {button to verify input}

  sANswer := Trim(edtAnswer.Text);
  sCode := edtCaptchaCode.Text;

  bRightAnswer := (sAnswer = sCode);
  bRightAnswer := True;

  bWrongAnswer := (sAnswer <> sCode);
  bWrongAnswer := False;

  if bRightAnswer then  
  begin
    btnCAPTCHAContinue.Show;
    Showmessage('Nicely Done, seems you''''re all set to go!'   #13  
                'Press the continue button to collect your codes young wizzling');
  end
  else begin
    edtCAPTCHACode.clear;
    edtAnswer.clear;
    btnCAPTCHAContinue.Hide;
    Showmessage( 'That seems to be the wrong answer, please try again');
  end;
end;

CodePudding user response:

That's because you first set bRightAnswer to true/false depending on whether it's correct, but then you immediately overwrite it again with a fixed true regardless of the condition. Same thing in the next block setting bWrongAnswer to false:

  bRightAnswer := (sAnswer = sCode); 
  bRightAnswer := True;     {regardless of what it was before, it's always true now}

  bWrongAnswer := (sAnswer <> sCode);
  bWrongAnswer := False;    {regardless of what it was before, it's always false now}

Remove those two lines.

You could further simplify the code by replacing bWrongAnswer := (sAnswer <> sCode); with bWrongAnswer := not bRightAnswer;, or going one step further and removing the bWrongAnswer variable entirely and just using not bRightAnswer everywhere in your code instead.

In fact, it seems that right now, you don't even use bWrongAnswer anyway, so there should be no damage in just removing it.

If you'd want to, you could also remove bRightAnswer and replace the if bRightAnswer then directly with if sAnswer = sCode then.

  • Related