JKJones
JKJones

Reputation: 15

Can you see why this if statement is not working correctly?

When i run this the if statement always returns false and thus doesn't run the two lines i have there. You can see in the above line i checked if the words are actually the same and they are identical. So is there something here that i am completely oblivious to or am i just screwed? If it matters i am using eclipse.

boolean wordHasElement = false;
for (int firstdimension = 0; firstdimension <= wordnumber-1; firstdimension++){
    System.out.println("-"+ words[firstdimension][0] + "-" + linewords[linewordnumber]  + "-");
    if (words[firstdimension][0] == linewords[linewordnumber] ){
        System.out.println("Worked");
        wordHasElement = true;
    }
}

Upvotes: 0

Views: 103

Answers (1)

Wallace Brown
Wallace Brown

Reputation: 612

if (words[firstdimension][0] == linewords[linewordnumber] ){

Should be replaced with

if (words[firstdimension][0].equals(linewords[linewordnumber] ){
  • == checks to see if one object is the same as another, which you really aren't interested in.
  • equals(...) checks if the two Strings hold the same string -- the same letters in the same order -- and that's what matters. Or you could use equalsIgnoreCase(...) if case doesn't matter.

Upvotes: 11

Related Questions