• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why won't my if statement pass?  RSS feed

 
Ian Tail
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I can't work out why my if statement won't pass? I'm reading in a word from a file, if the word matches a set string, then it should pass, if not then it should fail...

the contents of the file is the following sentence... "IAN IS TRYING IAN TO BUILD IAN SOMETHING"

Any help would be much appreciated

 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use == to compare objects.

The == operator compares objects by identity, not by value. Instead, use the equals() method.
 
Les Morgan
Rancher
Posts: 768
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ian,

You are suffering from the dreaded double equal comparison of String objects. If you look in the API many, if not most or all, of the object comparisons are done with a method, such as with the case of String using the String.equals() method you can look up in the API. The "==" operator comparison looks and says: "is this variable and that variable contain the same value. Well, in the case of String, an object, it does not because it is a reference to a String who's value is stored someplace in the Java references. So you will never get the case where "My String" == new String("My String") come evaluate to true, they simply reference different objects. The same is true when you read in the value from your scanner object, you're getting a new String when you do, so it will never evaluate to equal in a comparison using the double equals operator.

Les

Ian Tail wrote:Hi, I can't work out why my if statement won't pass?
 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few other issues:

There's no point in resetting your ref variable to "IAN" on every loop iteration. Declare ref outside of your while-loop and make it final, or even better, make it a private class constant:

You should be using try-with-resources to deal with readers. Here's what it would look like:
 
Ian Tail
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it working, great, thanks for your help and suggestions everyone!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!