mardi 24 novembre 2015

Java Check String Variable Length (with Substring)

I have a String variable which can have a different length every time it runs. With it, I check what it starts with, for example:

 public void defineLocation(){
            if (newLocation.substring(0,2).equals("DO") || newLocation.substring(0,2).equals("30") || newLocation.substring(0,2).equals("21")) {
                locationInDc = "DOOR";
            } else if (newLocation.substring(0,2).equals("VT") || newLocation.substring(0,3).equals("MUF")) {
                locationInDc = "BLOUBLOU";
            } else if (newLocation.substring(0,3).equals("MAH")) {
                locationInDc = "BLOBLO";           
            } else if (newLocation.substring(0,7).equals("Zone 72") || newLocation.substring(0,7).equals("Zone 70")){
                locationInDc = "BLOFBLOF";
}

I know this is not the most efficient way and it is bound to break as, if my variable is not in either of the first 3 checks but still has less characters than 7 then it will throw an error.

Is there a more "correct" way to do this? Should I check first how many characters the string contains and then point it to the right checks/"ifs"? Thank you.

Aucun commentaire:

Enregistrer un commentaire