Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Comparison Problem.

 
Brett Freedman
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First example: I set posTest to "C", display it and then test it for "C". The if statement works. playbyplayText is "CX".



Second example: I pull the "C" out of my teamplayer object. The "C" displays but the if statement does not fire. playbyplayText is only "C".




Here is my player class. I am reading the data out of a space delimited text file.

Why won't (posTest == "C") evaluate as true?

Sample data:



Declaration and class:

 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never use == for String comparison but use the equals method instead. == checks for instance equality whereas the equals method actually checks the String contents.
 
Brett Freedman
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is the complete code that builds the Player objects.

 
Brett Freedman
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Never use == for String comparison but use the equals method instead. == checks for instance equality whereas the equals method actually checks the String contents.


Fixed. Thanks Rob! I've been going around and around with that bit of code all day.
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic