lundi 15 juillet 2019

JAVA: Not going through if statement when it should be [duplicate]

This question already has an answer here:

I've got a fragment of a project I'm working on that simply will not work the way I want it to. I'm wanting to have a substring of the beginning of a string to be assigned to a new string, then thrown through if statements to do something, the issue is, the code isn't running through the if statement for some reason. It's probably somthing really simple that went right over my head. I just can't figure out what's wrong.

I've tried multiple different compilers, and nothing works. I've tried assiging the string directly in the code, and that works, but I would like to get the substring from a longer string.

public class ThingThatWontWork{
    public static void main(String []args){

        String infoNewsString = "KNM: blah blah blah";
        String curTargetString = infoNewsString.substring(0,3);

        System.out.println("infoNewsString: " + infoNewsString);
        System.out.println("curTargetString: " + curTargetString);

        if(curTargetString == "KNM"){
            System.out.println("**************************************");
            System.out.println("KNMMMM");
            System.out.println("**************************************");
        }          
        if(curTargetString == "BEN"){
            System.out.println("**************************************");
            System.out.println("BENNNNN");
            System.out.println("**************************************");
        }
    }
}

I expect the output to be the contents of the first if statement, however, the compiler never even runs through any of the if statements.

Aucun commentaire:

Enregistrer un commentaire