dyarosh
asked on
Java string comparison failing
I have a java method that passes in a string and is comparing the value in the string to a direction (i.e "East", "West", "North", "South"). When it finds a match it returns an Directions object (i.e Directions.East, Directions.West, Directions.North, Directions.South). I am making the call to the method as follows: convertDirection(eElement. getAttribu te("startD irection") );
Here is the method:
If the XML attribute contains "West", when I debug the method, dir shows "West" and the string length of dir is 4 so I don't have any extra unseen characters. However, the if(dir=="West") statement returns false so it doesn't return my West direction and falls through to the end of the method and returns North. If I hard code the call as follows:
convertDirection("West");
The method works correctly. I've tried creating a string variable and assigning the results of eElement.getAttribute("sta rtDirectio n") to the variable and passing that into the method but it still doesn't work.
Any help is greatly appreciated as I have to have this working by tomorrow morning and I am at a complete loss.
Here is the method:
private static Directions.Direction convertDirection(String dir)
{
System.out.printf("Direction in method: %s Length=%d\n", dir, dir.length());
if(dir=="East")
{
return Directions.East;
}
if(dir=="West")
{
return Directions.West;
}
if(dir=="North")
{
return Directions.North;
}
if(dir=="South")
{
return Directions.South;
}
return Directions.North;
}
If the XML attribute contains "West", when I debug the method, dir shows "West" and the string length of dir is 4 so I don't have any extra unseen characters. However, the if(dir=="West") statement returns false so it doesn't return my West direction and falls through to the end of the method and returns North. If I hard code the call as follows:
convertDirection("West");
The method works correctly. I've tried creating a string variable and assigning the results of eElement.getAttribute("sta
Any help is greatly appreciated as I have to have this working by tomorrow morning and I am at a complete loss.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Also, if Directions is an enum, you could use Directions.valueOf(dir) and it'll do the same thing in one line as the whole method you wrote. Be careful, though, because that method is case-sensitive and throws an IllegalArgumentException if the value doesn't exist.
ASKER
Thank you. That did the trick.