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(); } } }); } 

2 Answers 2

1

Change this:

if (word == word2) { 

with this:

if(word.equals(word2)) { 

You can't compare String with ==

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.