0
private boolean  CharToString(){
    String lineOfText = "XXXXXX";
    String desiredResult = "X";
    String actualResult = "initialised value";
    for(int i = 0; i < lineOfText.length(); i ++){
        actualResult = Character.toString(lineOfText.charAt(i));
        }
    if(desiredResult == actualResult){
        return true;
    } else{
        return false;
    }
}

So basically, this code is a reproduction of what I have, but designed to highlight what I believe the problem to be after a long time diagnosing and testing. As you can see, it sets the value of actualResult to the 'char' value of the character at the present location along lineOfText. Every value is intended to output "X" as a String (converted from char).

However, for reasons unknown to me, despite actualResult and desiredResult both outputting "X" to my debug drawText() method (I can't work out how to use console log...), the method returns false, indicating that the two String variables are NOT equal.

Strangely, if I were to change the if() else to a switch(), it would return true (i.e. work as intended).

I've tried Googling and searching StackOverflow but my search terms are probably poor/wrong as I'm getting no useful results :(

Any help would be greatly appreciated, and sorry if this is a stupid question - I have tried for ages to figure it out myself...

p.s. Is there a good graphic map editor available online anywhere? Editing a .txt file to create a map seems overly complicated, and very difficult to maintain consistency or coherence in the development of large/intricate maps... I figure there must be SOMETHING, how else would you make a 3D java game??

ZOMGbies
  • 51
  • 1
  • 1
  • 7

2 Answers2

1

Don't compare strings using ==. Always use equals(), as == only compares that they point to the same memory address, which they won't in this case.

private boolean  CharToString(){
String lineOfText = "XXXXXX";
String desiredResult = "X";
String actualResult = "initialised value";
for(int i = 0; i < lineOfText.length(); i ++){
    actualResult = Character.toString(lineOfText.charAt(i));
    }
if(desiredResult.equals(actualResult)){
    return true;
} else{
    return false;
}
}

That should do it

Rahul
  • 44,383
  • 11
  • 84
  • 103
maczikasz
  • 1,113
  • 5
  • 12
0

To compare 2 strings that refer to different memory locations you should use:

if(desiredResult.equals(actualResult) {
    return true;
} else {
    return false;
}

If the case would have been:

String desiredResult = "test";
String actualResult = desiredResult;

In this case you could use if(desiredResult == actualResult) , but using equals() would be better practice.

WonderWorld
  • 956
  • 1
  • 8
  • 18