简体   繁体   中英

Why equals might not return true

I have this string: "no_questions_by_user" in a variable named result.

than I do this check:

if ( result != null && result.equals( "no_user_id" ) )
{
        Log.d( "Post execute: " , "NOOOT  OKKKK - no user id" );    
}
else
if ( result != null && result.equals( "database_error" ) )
{
        Log.d( "Post execute: " , "NOOOT  OKKKK - database error" );    
}
else
if ( result != null && result.equals( "no_questions_by_user" ) )
{           
        Log.d( "Post execute: " , "NOOOT  OKKKK - no questions by user so far" );   
}
else
{
  Log.d( "MyQuestionsActivity" , "In JSON parsing area.." );                
}

and it always goes to the last else. But in my understanding it should really go to the block which checks result.equals( "no_questions_by_user" )

any idea why that block does not get executed?

Thanks!!

The code looks good. Your variable result must have another value.

My guess is that there are some whitespaces at the end or beginning of your result string.

Personally, I think this code is a hot mess.

I'd write one method that took in a result and looked up a message in a Map. All those if tests are making my eyes bleed:

private static final Map<String, String> LOG_MESSAGE_MAP;

static {
    LOG_MESSAGE_MAP = new HashMap<String, String>();
    // put all your result, message pairs in here
}

public void logResultDependentMessage(String result) {
    log.debug(LOG_MESSAGE_MAP.get(result));
}

Now adding new result, message pairs just means inserting into the map. If you're using something like Spring you can do it in configuration and not touch the code.

尝试:

result.trim().equals( "no_questions_by_user" )

Did you see "no_questions_by_user" in a debbugger ?

You can try to trim it before the test, as spaces are hard to detect in debuggers.

Make sure there are no white spaces in the value of the "result" variable. Before entering the if statements, you can do a print line like this one.

System.out.println("The Value of result variable is=\"" + result + "\"");

You might as well do this

if ( result != null && result.trim().equals( "no_questions_by_user" ) )
{           
        Log.d( "Post execute: " , "NOOOT  OKKKK - no questions by user so far" );   
}

我建议您使用一些静态变量来存储您的字符串,从而避免键入错误。

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