简体   繁体   中英

Java not comparing correctly two equal strings

I'm confused as this shouldn't be an issue, I load data from a file to a List of classes and then I check from user input - a string. If the string is equal when comparing, then a few variables extracted from the file should be printed.

public static Double[] buscarLocacion(String estado,String municipio){

    Double[] coord = { 0.0, 0.0 };       
    for(Ubicacion i: ubicacion) {

        System.out.println("check: "+estado +" getEstado:"+ i.getEstado() + " ==: " +i.getEstado().equals(estado));

        if(i.getEstado().equals(estado)) {
            if(i.getMunicipio().equals(municipio)) {

                coord[0] = i.getLat();
                coord[1] = i.getLon();
                return coord

        //etc..

I made a separate class with a main function. This works as expected, the program prints this when the string is equal:

found: hidalgo - tula de allende lat:20.0535516 lon: -99.3395636

However when I import this class into another, when doing the comparison, I always get null. I printed what is comparing and if the program founds the comparison is true or false like this:

System.out.println("check: "+estado +" getEstado:"+ i.getEstado() + "  equals?=: " +i.getEstado().equals(estado));

and this code prints this:

check:  yucatan file:veracruz de ignacio de la llave ==: false
check:  yucatan file:yucatan ==: false //<<<- how is this possible??
check:  yucatan file:oaxaca ==: false

Any ideas why this is happening? I can not find the problem. What am I doing wrong here?

Your input may contain whitespace. For example, " yucatan" .

Probably the problem is with the "i" or with heading or trailing whitespace. Try the following:

public static  Double[] buscarLocacion(String estado,String municipio){

    Double[] coord = { 0.0, 0.0 };

     for(Ubicacion i: ubicación){
         String iEstado = i.getEstado().trim();
         estado = estado.trim();

         System.out.println("check: "+estado +" getEstado:"+ iEstado + " ==: " +iEstado.equals(estado));


            if(iEstado.equals(estado)){
                String iMunicipio = i.getMunicipio().trim();
                municipio = municipio.trim();

                if(iMunicipio.equals(municipio)){

                coord[0] = i.getLat();
                coord[1] = i.getLon();
                 return coord

//etc..

I have had this kind of errors before, and although I am not sure why this happens, this should fix your code. If it does, you can try to change the order of the comparison:

estado.equals(i.getEstado());

and check if this way it works (not to have to create additional variables).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM