Lazarus

Programming => General => Topic started by: dfergfla on September 25, 2017, 03:48:24 am

Title: If then else
Post by: dfergfla on September 25, 2017, 03:48:24 am
I am just started playing around with Lazarus again.  I kind of played with it a few years ago.  I'm not a programmer but used to play with pascal way, way back in the 80's, ya I'm that old.  Anyway, so i am up to my eyeballs in what will be stupid questions to the people here.  But, i will never get anywhere if I don't ask.  The last programming language I toyed with in any serious way was VB 5 and that was well over 20 years ago.  So, now for my stupid question.

I was playing around trying to get comfortable with If then else.  But tried something that doesn't work and I thought it should.  I am clearly wrong and now I want to figure out how.

I have a button on a form and was trying to use an if then else statement to evaluate the text of the caption and change it...into something else and it looked like this....

If Button1.Caption := 'Yes' then
   Button1.Caption := 'no';

I am getting an error :unit1.pas(35,13) Error: Incompatible types: got "untyped" expected "Boolean"

I do know that If Then Else has to be boolean, but I thought this type of thing would eval to a yes or no.
So, how would I do this?


Thanks :)

Newbie
Title: Re: If then else
Post by: molly on September 25, 2017, 04:12:30 am
Just a quick question to see if you are able to help yourself:

How would Button1.Caption := 'Yes' evaluate to a boolean ?
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 04:17:55 am
@molly

Ya,  I realized that I was way off...but now I just can't seem to figure out how I would do something like that at all, never mind using If Then Else.  Would a case statement work?
Title: Re: If then else
Post by: molly on September 25, 2017, 04:29:10 am
Just to make sure: you do know the difference between an assignment (https://www.freepascal.org/docs-html/ref/refsu52.html) and a boolean expression (comparison (https://www.freepascal.org/docs-html/ref/refsu50.html#x153-17500012.8.6) in this case) ? see also  if-then-else definition (https://www.freepascal.org/docs-html/ref/refsu57.html#x163-18500013.2.3)

Yes, a case statement would work as well.

edit: added links
Title: Re: If then else
Post by: Bazzao on September 25, 2017, 04:40:07 am
dfergfla,

A hint (trying to keep Mollys efforts intact).

Perform a Colectomy (Colectomy is surgery to remove the colon).
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 04:50:31 am
@ molly

Thanks for the links.  I had an ok(ish) understanding but better now.  I'm going to go lookup case statements and play with that.

You said case would work as well.  may I ask what you would do, if not case?

Thanks again.

Title: Re: If then else
Post by: molly on September 25, 2017, 05:08:07 am
@dfergfla
I have two choices there: either paste the answer or let you memorize a very important lesson (for a very long time, because you came up with the answer on yourself).

I would use a if-then-else construction if not using a case statement.

So, what would you prefer i do ?

@Bazzao:
thank you. it is a very good hint because i even had to read that twice before it 'hit' me  :D
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 05:38:38 am
I found TryStrToBool

But, the example isn't sinking in for me...

procedure TForm1.ToggleBox1Change(Sender: TObject);
var true : boolean;
begin
  if Button1.Caption:= TryStrToBool('test' , true) then
     Button1.Caption:= 'no test';
end;
       

gives me an err:   unit1.pas(36,52) Error: Incompatible type for arg no. 1: Got "Boolean", expected "TTranslateString"

I am also trying to learn how to read what the debugger is trying to tell me...

Title: Re: If then else
Post by: molly on September 25, 2017, 05:51:33 am
small advise: stick to the first error "Error: Incompatible types: got "untyped" expected "Boolean" as that is easier to grasp.

You're thinking waaay out of the box in your last attempt.

What the compiler is trying to tell you in the first error is that it is expecting a boolean (or expression that evaluates to a boolean result value) but it got a untyped of something instead.

Pascal is for instance not like c where every assignment is checked against zero and evaluates to a true or false value by some complicated compiler magic that nobody is able to explain when a statement get too complicated to comprehend.

Pascal needs you to be explicit, also in this case. Doing an assignment alone is not a boolean expression and will also not evaluate to a boolean.

So, a boolean expression is required. I already linked to some of the operators that you could use to 'make' a boolean expression.

So
  X := Y would assign (https://www.freepascal.org/docs-html/ref/refsu52.html#x157-17900013.1.1) Y to X
and
  X <> Y would be a expression (https://www.freepascal.org/docs-html/ref/refch12.html#x139-16100012) that evaluates to a boolean that could be used for instance in a if-then-else construction.

edit: reworded and added links

edit2: finally i was able to find a link that has things summed up using simple words (i hope), here (https://en.wikibooks.org/wiki/Delphi_Programming/Boolean_expression).
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 06:36:05 am
 ya.. way outside the box.  Thanks for the link.  and for the help.
Title: Re: If then else
Post by: molly on September 25, 2017, 06:57:58 am
Sorry dfergfla as it still is not the copy-paste answer that you are probably be looking for, but i think i provided enough information for you to be able to distinguish between an assignment and a comparison operator.

If that difference has reached your understanding then please do come back and show us. As for your example of comparing, assigning and changing the button caption there is much more to tell/learn then only the difference between an assignment and a comparison.

Just say the word and i will paste the literal answer to your question, with some additional notes about why you can't solve this gracefully with using the (fixed) code from your snippet alone.
Title: Re: If then else
Post by: Bazzao on September 25, 2017, 07:03:51 am
Molly,

My turn ...

Colonize (add a colon to) assignments and decolonize (remove colon from) expressions.

B
Title: Re: If then else
Post by: molly on September 25, 2017, 07:21:39 am
@Bazzao
Fair enough, i gave it my best shot and that didn't seem to be able to do the trick :-[

It's a very important lesson to learn though so i discarded just pasting the answer.

This kind of basic understanding should be part of the standard programming vocabulary otherwise the same questions will be asked over and over again and prohibits healthy progress. And yes, when i started out with Pascal (or any other language for that matter) i made the same stupid mistakes as any n00b makes, as i dislike reading manuals as well  :)
Title: Re: If then else
Post by: balazsszekely on September 25, 2017, 08:03:12 am
Stop torturing the man. I did the same mistake a few days ago. I was staring my monitor 30 seconds before I realized what is wrong.  :D For a beginner is a perfectly understandable mistake.
Title: Re: If then else
Post by: munair on September 25, 2017, 08:12:13 am
Given your own example, apparently you know that the '=' operator in Pascal is not always the same as in VB. You should read a bit more about that first.
Title: Re: If then else
Post by: mangakissa on September 25, 2017, 11:51:39 am
Quote from: GetMem
Stop torturing the man. I did the same mistake a few days ago. I was staring my monitor 30 seconds before I realized what is wrong.  :D For a beginner is a perfectly understandable mistake.
100% agree.

@Molly why not givving the right answer with an example?

@dfergfla
with ':=' you assign a value to a variable. Using if ..  then pascal using '='

Code: Pascal  [Select][+][-]
  1.   if button1.Caption = 'Yes' then
  2.     button1.Caption := 'No';
  3.  
Title: Re: If then else
Post by: munair on September 25, 2017, 12:20:43 pm
@Molly why not givving the right answer with an example?
Because it's too easy. If one needs to do some brushing up like in this case, reading is the way to go, which can be done very comfortably using internet where you can find answers within minutes. If a compiler complains, finding out why on your own is the best way to understand that compiler, so you won't make that mistake again.
Title: Re: If then else
Post by: molly on September 25, 2017, 12:39:14 pm
@Molly why not givving the right answer with an example?

0) the term self-sufficiency seems not well spend on your person (no offense)
1) i opted for a quick way out, TS did not responded to that,. In fact no other feedback whatsoever was provided other then thanks for the links.
2) i explained the thing into detail, again no feedback whatsoever other than thanks
3) every link i posted either provided an example or links to an example showing the literal difference between := and =

But i get it: just blame it on someone else and we can sleep well at night again :P

Remind me to never go on a survival with you  ... it will most definitely kill me   :D
Title: Re: If then else
Post by: RAW on September 25, 2017, 03:03:30 pm
Or like this...  :)

Code: Pascal  [Select][+][-]
  1. Procedure TForm1.FormClick(Sender: TObject);
  2.  Begin
  3.   Case Button1.Caption
  4.   Of
  5.    'YES': ShowMessage('YES');
  6.    'NO' : ShowMessage('NO');
  7.    '123': ShowMessage('123');
  8.    '456': Begin
  9.            Color            := clBlack;
  10.            Button1.Caption  := 'YES';
  11.            Button1.SetBounds(0, 0, 100, 50);
  12.           End;
  13.    Else ShowMessage('Something else...');
  14.   End;
  15.  End;
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 06:50:35 pm
@ molly and everyone

I did get it.  Even before I saw the sample code posted here.

Here is my solution:

  if (Button1.Caption = 'Test 1') then
     Button1.Caption := 'Test 2' else
       if (Button1.Caption = 'Test 2') then
          Button1.Caption := 'Test 3' else
               Button1.Caption := 'Done'     
                                           

I am not sure I needed the parenthesis

Just in case you were interested this is what gave me the clue as to what I was doing wrong.
"Colonize (add a colon to) assignments and decolonize (remove colon from) expressions."
It was right there in front of me, I just couldn't see it.

Donald (aka Newbie)
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 06:52:21 pm
@ Raw

I don't really understand everything you have there, but I am going to start playing with case statements today.


Thanks
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 06:55:12 pm
@ Raw

How exactly did you get the copy and pate to come from the IDE like that?
Title: Re: If then else
Post by: RAW on September 25, 2017, 07:19:09 pm
Quote
I am not sure I needed the parenthesis
Not in this case, but it's easy to check this for yourself, isn't it..?  :)

But in this case:
Code: Pascal  [Select][+][-]
  1. Procedure TForm1.FormClick(Sender: TObject);
  2.  Begin
  3.   If (Button1.Caption = 'Hallo') And (Button1.Top > 70)
  4.   Then ShowMessage('YES');
  5.  End;

Quote
How exactly did you get the copy and pate to come from the IDE like that?
The usual way:
1. CTRL+C
2. Press the "#"-Button (Insert Code-Button)
3. Place the cursor between (code=pascal) and (/code)
4. CTRL+V
5. Click On Preview...
Title: Re: If then else
Post by: dfergfla on September 25, 2017, 07:53:28 pm
I've been playing around  :D

Code: Pascal  [Select][+][-]
  1. begin
  2.   if Button1.Caption = 'Test 1' then
  3.      begin
  4.      Button1.Caption := 'Test 2';
  5.      Form1.Color := clBlack;
  6.      end
  7.      else
  8.        if Button1.Caption = 'Test 2' then
  9.           Button1.Caption := 'Test 3' else
  10.              begin
  11.              Button1.Caption := 'Done';
  12.              Form1.Color:=clDefault;
  13.              end;
  14.  
  15. end;  ;
Title: Re: If then else
Post by: RAW on September 25, 2017, 08:58:22 pm
Quote
Form1.Color := clBlack;
Try
Code: Pascal  [Select][+][-]
  1. Self.Color:= clBlack;
Or just
Code: Pascal  [Select][+][-]
  1. Color:= clBlack;
... just in case you want to rename the form (Form1)... :)
Otherwise you need to rename the whole source code if you change the name of the form.
Title: Re: If then else
Post by: Thaddy on September 25, 2017, 08:59:19 pm
Code: Pascal  [Select][+][-]
  1.   case Button1.Caption of
  2.   'Test 1':Button1.Caption := 'Test 2' ; // will not reach test2
  3.   'Test 2':Button1.Caption := 'Test 3';
  4.   else
  5.      Button1.Caption := 'Done';
  6.   end;

Note that Pascal syntax does not allow for fall-through, like is possible with C syntax     
Similar answer to RAW's
                                           
Title: Re: If then else
Post by: dfergfla on September 26, 2017, 12:09:59 am
@ Thaddy

Thanks, been playing around with it for a little bit.  How would I do more than one thing given a case?

Like change the button caption and the form color if Button1.Caption := 'test 2'

In the if then else I used
Code: Pascal  [Select][+][-]
  1. begin
  2.    Statement 1
  3.    Statement 2
  4. End

but that doesn't work with case.  I tried looking up examples but could not find one that executed more than one statement per case.
Title: Re: If then else
Post by: dfergfla on September 26, 2017, 02:56:50 am
got it  :)

Code: Pascal  [Select][+][-]
  1.   case Button1.Caption of
  2.   'Test 1':
  3.     begin
  4.     Button1.Caption := 'Test';
  5.     self.Color := clBlack;
  6.     end;
  7.   'Test 2':Button1.Caption := 'Test 3';
  8.   else
  9.      Button1.Caption := 'Done';
  10.      self.color := clRed
  11.   end;
Title: Re: If then else
Post by: dfergfla on September 26, 2017, 03:10:11 am
Question:

This works as expected.  The color changes each time:
Code: Pascal  [Select][+][-]
  1. begin
  2.   case Button1.Caption of
  3.   'Test 1':
  4.     begin
  5.     Button1.Caption := 'Test 2';
  6.     self.Color := clBlack;
  7.     end;
  8.   'Test 2':
  9.     begin
  10.     Button1.Caption := 'Test 3';
  11.     Self.Color := clRed ;
  12.     end;
  13.   else
  14.      begin
  15.      Button1.Caption := 'Done';
  16.      self.Color := clDefault;
  17.      end;
  18.   end;
  19.   //self.color := clDefault

In this case the color always stays at default
Code: Pascal  [Select][+][-]
  1. begin
  2.   case Button1.Caption of
  3.   'Test 1':
  4.     begin
  5.     Button1.Caption := 'Test 2';
  6.     self.Color := clBlack;
  7.     end;
  8.   'Test 2':
  9.     begin
  10.     Button1.Caption := 'Test 3';
  11.     Self.Color := clRed ;
  12.     end;
  13.   else
  14.      begin
  15.      Button1.Caption := 'Done';
  16.      //self.Color := clDefault;
  17.      end;
  18.   end;
  19.   self.color := clDefault

Never mind, I figured out why.

Thanks
Title: Re: If then else
Post by: PatBayford on September 26, 2017, 07:29:10 am
Yes, stop torturing the poor soul - it's a mistake we've all made, especially those of us who use more than one programming language.
In Pascal A := 99 sets A to the value 99, whereas If A=99 tests A to see if it has the value 99.
The latter form is used when doing comparisons, and returns a Boolean (i.e. True or False).
Title: Re: If then else
Post by: RAW on September 26, 2017, 01:21:27 pm
Quote
In this case the color always stays at default
Yes, of course, you set the Color to clDefault outside the CASE statement and at the end of the procedure, so the last thing the procedure does is setting the DEFAULT color....
Title: Re: If then else
Post by: cpicanco on September 26, 2017, 07:54:40 pm
"Because it is too easy" does not describes problems that "giving an answer" may cause for someone. It also does not describes advantages it may have, depending on the circuntances. So here we go:

Programming, as an educational endeavor, as a tech enterprise, have some pretty complicated challenges. If you are in a tech company, or is an independent tech professional, you will have competitive advantage if you live in a workplace (or open community) that promotes autonomy to solve problems, to research about themand to communicate efficiently in order to colaborate around them. It is not that hard to recognize that both autonomy and colaboration are imperative for the enterprise success.

But how to colaborate efficiently and also promote autonomy (auto-regulation, auto-management, as you wish), speacially in open communities? Foolish joking, unjustified public embarrassment, bullying and so on are not the answer.

Should you copy-paste an answer from this very forum?

It depends on you (and your environment). If you choose to copy-paste, you should also have a proper understanding of what you are doing, legally, logically, ethically and so on. You should be honest with yourself by linking (in the paste location) to the post from where you copy, even if you have adapted the code. You should understand the code before running it, for the sake of your own safety and productivity. Many things can generate unexpected addiction that, in turn, will block your motivation. Disoriented copy-paste is one of them.

Should you answer a question by giving the answer?

It depends on the question. For this especific question, I can't think of a single reason to not give the answer. I would do it this way:

Note that in pascal the assigment operator is := and the equal operator is =. Please, try again with this information. Also, for more info about pascal operators see:

Assigment operator
https://www.freepascal.org/docs-html/ref/refsu52.html#x157-17900013.1.1

Equal operator
https://www.freepascal.org/docs-html/ref/refsu50.html#x153-17500012.8.6

How to read sintax diagrams?
https://www.freepascal.org/docs-html/ref/refli5.html#x6-5000

Title: Re: If then else
Post by: munair on September 27, 2017, 09:46:42 am
@cpicanco: Yes it does. If you do programming in a specific language, you are supposed to know exactly what you do when you write a statement. Even beginners. When I start with a new language (it wasn't all that long ago that I started with Pascal relatively speaking) I usually get a book or reference guide showing me the basics. The asignment and equal operators in Pascal are SO fundamental, it is one of the first things if not THE first thing I learned. And coming from BASIC-like languages I had to make the same mistake several times before it really sank in.

Assignment is not the same as comparison and Pascal forces the programmer to know the difference, which I believe is a great thing.

This topic was essentially unnecessary IF the OP would have taken the time to figure out the basics. Instead he jumped at the forum to get a quick answer. THAT is too easy. BTW in my comment I literally gave the answer, but I left it to the programmer to see the logic and correct the code himself.
Title: Re: If then else
Post by: molly on September 27, 2017, 10:06:41 am
@ molly and everyone
I did get it.  Even before I saw the sample code posted here.

It was right there in front of me, I just couldn't see it.
Yes, i was aware that you already had your face-palm moment before i even wrote that post.

fwiw: I was not trying to bash your silence there. Since some people seem stuck in twitter mode, i summarized the thread. Harsh words seems required to get the message across (in a tweet).

Quote
Just in case you were interested this is what gave me the clue as to what I was doing wrong.
"Colonize (add a colon to) assignments and decolonize (remove colon from) expressions."
tbh i thought the first clue from Bazzao was a much better one, but in the end it only matters what works for you (e.g. if it can work as a reminder for you)
Title: Re: If then else
Post by: cpicanco on September 27, 2017, 10:18:36 pm
Quote
When I start with a new language (it wasn't all that long ago that I started with Pascal relatively speaking) I usually get a book or reference guide showing me the basics

Good for you. Are you assuming that OP knows how to access and how to find these resources?

Quote
And coming from BASIC-like languages I had to make the same mistake several times before it really sank in.

You should not assume that because it was hard for you that it must be for others too.

Quote
This topic was essentially unnecessary IF the OP would have taken the time to figure out the basics. Instead he jumped at the forum to get a quick answer.

You were assuming OP had a bad attitude and you are assuming that he thought this forum is a way to get a "quick answer". Sorry dude, I think you are assuming too much.
 
Title: Re: If then else
Post by: munair on September 28, 2017, 09:52:20 am
Quote
When I start with a new language (it wasn't all that long ago that I started with Pascal relatively speaking) I usually get a book or reference guide showing me the basics

Good for you. Are you assuming that OP knows how to access and how to find these resources?

Quote
And coming from BASIC-like languages I had to make the same mistake several times before it really sank in.

You should not assume that because it was hard for you that it must be for others too.

Quote
This topic was essentially unnecessary IF the OP would have taken the time to figure out the basics. Instead he jumped at the forum to get a quick answer.

You were assuming OP had a bad attitude and you are assuming that he thought this forum is a way to get a "quick answer". Sorry dude, I think you are assuming too much.
Yes dude, if one knows how to find its way to the forum, then assuming that one knows how to use google as a start, isn't being unrealistic.

But it is nice mirroring you display here assuming "it was hard for me". No it wasn't. I just gave an example that applies to many if not most coming from another programming language.

I also did not "assume" the OP had a bad attitude. Asking for a quick answer isn't exactly something I would call bad. What I was trying to say is that I perfectly understand why a copy-paste answer wasn't given right away.

It looks like you're exaggerating here for whatever reason and you like to reflect things back at me while it is not at all about me. I was giving some examples in light of the OP having programming experience, according to his own words.

But thanks a lot for your opinion, dude. Now I end this conversation because it is going way off topic.

Note: Edited.
Title: Re: If then else
Post by: Yukiko on October 07, 2017, 02:01:22 am
Let me start my comment on this thread by saying that I have generally found the Lazarus/Free Pascal community very friendly and helpful.

Though my initial experience with Pascal was a very long time ago, 1980s for anyone who cares. I came to discover the Lazarus project 9 years ago and I believe back then some many people must have helped me right here on the forums because I started a project then and for some unexplained reason abandoned it, absolutely forgot I had ever started it then rediscovered it 9 years later, and pardon the word play here, resurrected it (those who know the Biblical story of Lazarus will get it  :D ), and I can't believe I had written the code. Evidence that this community obviously helped me because I am a mediocre programmer at best.

On the subject of a quick answer I'd say yes feel free to give one but along with that either give some explanation to help educate the person or post links for further reading. How you phrase the "quick answer" can provoke a learning experience in itself. The person who gave the answer
Quote
Colonize (add a colon to) assignments and decolonize (remove colon from) expressions.
didn't actually give what I would call a quick answer. I apologize that I don't remember your name. A quick answer in my opinion would have been to post corrected syntax of the 'if' statements.

I don't have a problem with "quick answers" generally. Sometimes someone is trying to get something to work in the moment and they may not have time to take a course in object Pascal. If the same person keeps coming back with "pre-school" programming questions then it's time to point them to online tutorials such as Lut has written (http://sheepdogguides.com/lut/index.htm). Many of us are not working in an "enterprise" or work related programming job. Some are just needing to explore our ability to create something and others like myself are working as a developer for free on an open source project and don't have the money or time to learn all the ins and outs of object Pascal. So sometimes a quick answer is enough.

On the subject of documentation I have found the CHMs and PDFs to be both helpful and frustrating. The CHMs are particularly frustrating because there are many "broken links" that give the error can't find page or something similar. I have found the Free Pascal wiki (http://wiki.freepascal.org/) to be the most helpful place to go to find help on my own though many of the concepts that it is assumed I am supposed to understand are still above my level. Honestly, as someone else pointed out, a search engine is often very helpful, much more so than the included documentation with Lazarus.

Now to my final comment. Yeah I know you're all sighing with relief. :)
I appreciate the help I have received here. I hate to see the answer to a simple question turn into such a contentious thing. Both sides were right. You should learn the basics of the syntax of the language you are programming in and sometimes a quick answer is all that is needed. I can't tell you how many times I have sat and spent sometimes hours looking at some piece of code I had written trying to figure out why it isn't working only to have someone look over my shoulder and say "you're using a greater than when you need a less than equals operator" or some such thing. Of course I knew that but I was not seeing the "trees for the forest" to twist a metaphor. The code had gotten in the way and I totally overlooked the detail.

Thanks again for all the help I have received over the years.
TinyPortal © 2005-2018