• Post Reply Bookmark Topic Watch Topic
  • New Topic

if statement and keycodes

 
Alex Hayes
Greenhorn
Posts: 7
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I have just recently started coding in Java, and I have come up with a problem: Why does this Key Event activate even if the if statement around it is not true? The problem is that I don't want to print "It works" before I press 1 on the key board, but it does any way. Help please?
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

That's your problem there: if(c1 = true). That is an assignment of true to c1, not a comparison. And in Java an assignment returns the value being assigned. So that statement will always be true. The comparison would look like this if(c1 == true), but the explicit comparison to true is unnecessary and should be avoided to prevent just such mistakes (which are way more common than you would think). Do this instead: if (c1) {.
 
Alex Hayes
Greenhorn
Posts: 7
Eclipse IDE Java Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, I know it was more of a noobish question, but it helps to know minor stuff like this and not have problems later.
 
Campbell Ritchie
Marshal
Posts: 52543
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!