0

So I have been writing a game and was looking to make the code base more useable. I originally wrote the following code once and worked fine. But for reuse and fewer lines, I was adjusting it. Now it's not working

Main java file:

builder.setStats("p, divine,0,1,2,2,1,2,4");

Builder file:

String [] holder = new String[8];

public void setStats(String sentstats){
     holder = sentstats.split(",",8)

     if(holder[0]== "p"){
         charsheet.style = holder[1];
     }
}

So the issue is the if never does the proper response. I know I have full access to all associated files as I have tested for that. And I know I could get it to work other ways. But to reduce redundancy. And make parts of the code recursive I have done it like this.

2 Answers2

0

Use equals() instead of == as you are using String not a character

From:

 if(holder[0]== "p"){
     charsheet.style = holder[1];
 }

, To:

 if("p".equals(holder[0])){
     charsheet.style = holder[1];
 }
0xh3xa
  • 4,801
  • 2
  • 14
  • 28
0

Stings are not primitive types in Java. They are treated like objects. When you use == for objects, Java checks if both objects have the same reference in memory rather than checking for the values (or similarities in global values) between both objects. This means that Java doesn't care what the values of the strings are; as long as they are not the exact same object referenced in memory, Java will return false. Therefore, you should use equals() or compareTo(), both of these methods actually check the value of the string rather than checking if both objects have the same reference.

METHOD 1

if("p".equals(holder[0])){
    charsheet.style = holder[1];
}

METHOD 2

METHOD 1

if("p".compareTo(holder[0]) == 0){ //compareTo returns 0 if both strings equal
    charsheet.style = holder[1];
}