1

I have an array of buttons which contains two elements.
I'd like to create a string from the text of the buttons.
The thing i am struggling with is the if statement. Basically, it is never firing the toast. Why?

String word2 = "ok";

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

    final Button buttons[] = new Button[2];

    buttons[0] = (Button) findViewById(R.id.btn);
    buttons[1] = (Button) findViewById(R.id.btn2);

    buttons[0].setText("o");
    buttons[1].setText("k");

    buttons[0].setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String word = "";
            for (int i = 0; i < 2; i++) {

                word += buttons[i].getText().toString();
            }

            if (word == word2) {
                Toast.makeText(getApplicationContext(), "Good",
                        Toast.LENGTH_LONG).show();
            }

        }
    });
}
Toumash
  • 1,077
  • 11
  • 27
Endi Tóth
  • 221
  • 3
  • 15

2 Answers2

1

Change this:

if (word == word2) {

with this:

if(word.equals(word2)) {

You can't compare String with ==

aletede91
  • 1,137
  • 2
  • 16
  • 30
1
  1. Write Better Questions (basically questions)
  2. Compare string with .equals() not ==.
    Just use if(word.equals(word2) {

Why? The first one is content comparision, but the second one i just a reference comparision so:

String a = new String("x"); 
String b = new String("x"); 
if(a==b){
    System.out.println("It wont work");
}else if(a.equals(b)){
    System.out.println("It will");
}

Dont ever use new String(), it was just for proof

  1. I must write it.

Change line

for (int i = 0; i < 2; i++) { 

into

for (int i = 0; i < buttons.length; i++) {

So your application will be easier to change

Community
  • 1
  • 1
Toumash
  • 1,077
  • 11
  • 27