Victor Mihaita
Victor Mihaita

Reputation: 116

If statement returns only the result from the "else" statement

I am trying to make a script that compares the user input with another string. The problem is with my if statement. I don't get errors but it always returns the result that is in the "else" statement. Here is the code:

String [] lessons_titles = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","30","40","50","60","70","80","90"};

final TextView dan_view = (TextView)findViewById(R.id.DanText);
final int position = getIntent().getExtras().getInt("position");
final String title = lessons_titles[position];

check_b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String textField = check_text.getText().toString();
            if (textField == title){
                dan_view.setTextColor(Color.GREEN);
            }
            else {
                dan_view.setTextColor(Color.RED);                   
            }                           
        }
    });

Upvotes: 0

Views: 97

Answers (5)

Hamid Shatu
Hamid Shatu

Reputation: 9700

Use equals() method instead of == operator when you compare String. In case of String, two string will be equal if their reference are same and to find out that both of them referencing to the same point, you have to use equals() method. == operator can only compare primitive type value but instance of String is object.

So, your condition should be as follows...

if (textField.equals(title)){
    dan_view.setTextColor(Color.GREEN);
} else {
    dan_view.setTextColor(Color.RED);
} 

Upvotes: 3

Ray
Ray

Reputation: 1214

"textField == title" Using == will check that they are the exact same, not just value wise but also stored in the same memory location.

Instead try using if (textField.equals(title)){

A good example is shown here http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

Upvotes: 0

wael
wael

Reputation: 454

use this

 if (textField.compareTo(title) == 0)
 {
   dan_view.setTextColor(Color.GREEN);
 }
  else {
      dan_view.setTextColor(Color.RED);                   
  }     

Upvotes: 0

Pararth
Pararth

Reputation: 8134

== is for testing whether two strings are the same object; - reference equality.

You want to check the value so should use .equals()

Take a look at:

http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

for further clarification.

Upvotes: 1

nook
nook

Reputation: 2396

Your error is here:

if (textField == title){ //<--

textField is a string, you need to check string equality using .equals(), e.g.

if (textField.equals(title)){ //<--

Upvotes: 0

Related Questions