0

I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:

 String word = textfield1.getText().toString(); String answer = textfield2.getText().toString(); textfield2.setText(textfield2.getText().toString()); if(word == answer){ Toast.makeText(getApplicationContext(), "correct", Toast.LENGTH_LONG).show(); }else Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show(); } 

However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?

1
  • I think object may compare the == ,if you want compare the two string use equals and equalignorecase likethat functionlity. Commented Dec 23, 2014 at 3:49

5 Answers 5

3

You can't compare strings with the == operator.

Use .equals() instead:

if(word.equals(answer)) { //do whatever } 
Sign up to request clarification or add additional context in comments.

Comments

2

Use String.equalsIgnoreCase for comparing content of both string variables.:

 if(word.equalsIgnoreCase(answer)){ } 

Comments

1

Use:

String word = textfield1.getText().toString(); String answer = textfield2.getText().toString(); if(answer.contentEquals(word)){ // Do something if equals } else{ // Do something if not equals } 

1 Comment

It's workin.Thanks I used if(!question.contentEquals(ans)) for negatve level.
1

I think the best way to do this is using TextUtils:

if(TextUtils.equals(textfield1.getText(),textfield2.getText())){ //do something } 

Comments

0

instead of

 if(word.contentEquals(answer)){ } 

Use

 if(word.equals(answer)) 

as we cant compare strings with Equal to (==) operator

Try This::

String word = textfield1.getText().toString(); String answer = textfield2.getText().toString(); if(word.equals(answer)){ Toast.makeText(getApplicationContext(), "correct", Toast.LENGTH_LONG).show(); }else Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show(); } 

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.