-1

i'm making an anagramm app in android. I have some problem, i have buttons with text "A", "B", "C" for example. My code generate string "ABC", and my ans[i] = "ABC". But when i compare them, it returns me false. Help pls.

There are code example, i have problem in

if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();

public class MainActivity extends AppCompatActivity {
public List<Button> btns;
public List<String> ans;
String word = "";
String checkStr;
EditText text;
private static final int[] btn_id = {
        R.id.btn1,
        R.id.btn2,
        R.id.btn3,
        R.id.btn4,
        R.id.btn5,
        R.id.btn6,
        R.id.btn7,
        R.id.btn8
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btns = new ArrayList<Button>();
    ans = new ArrayList<String>();
    text = findViewById(R.id.txt);
    text.setEnabled(false);
    fillAnswers();

    for (int i = 0; i < btn_id.length; i++){
        Button b = findViewById(btn_id[i]);
        btns.add(b);
    }
}

public void fillAnswers(){
    ans.add("ERATO");
    ans.add("MARI");
    ans.add("AIR");
}

public void onClick(View v){
    Button b = (Button)v;
    char str = b.getText().charAt(0);
    addToString(str);
    text.setText(word);
    b.setEnabled(false);
   // Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
}

public void okClick(View v){

    //Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
    if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
  /*  for (int i = 0; i < 3; i++){
       // Toast.makeText(this, word, Toast.LENGTH_SHORT).show();

        if (checkStr == ans.get(i)){
            Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
        }
    }*/

    word = "";
    text.setText(word);
    for (int i = 0; i < btn_id.length; i++){
        Button b = findViewById(btn_id[i]);
        b.setEnabled(true);
    }
}

public void addToString(char s){
    word += s;
}

}

Ordec
  • 89
  • 1
  • 1
  • 9

1 Answers1

0

You have to compare string values with equals

ans[i].equals("ABC");

Or

if (word.equals("ERATO")) Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
mac229
  • 4,319
  • 5
  • 18
  • 24
  • Thanks, that works. But why "==" doesnt work? – Ordec Dec 03 '17 at 23:23
  • That's because .equals compares the values of the string, and == checks if two objects have same value in the memory. Do take a look at String functions like .equalsIgnoreCase(). – Harshita Dec 04 '17 at 03:00
  • @Ordec if I help you, you should upvote my answer and check as correct on the left side – mac229 Dec 04 '17 at 08:29