0

I have a string "sss" and a character array {'s','s','s'}. I converted the array to string but the message "both are equal" is not printed upon comparing them. Why?

public class RoughActivity extends Activity 
{
 private Button checkButton;
 private TextView text;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
        start();
        }

        private void start() {
            int i;
            checkButton=(Button)findViewById(R.id.go);
            text=(TextView)findViewById(R.id.display);
            final String question="sss";
            final char answer[]=new char[question.length()];
            for(i=0;i<question.length();i++)
            {
                answer[i]='s';
            }
            checkButton.setOnClickListener(new View.OnClickListener(){ //on clicking the button,the text must be filled with "both are equal"
                public void onClick(View v){
                    if(question.equals(answer))
                    {
                        text.setText("both are equal");
                    }


                }});
}
}
1
  • 1
    you are trying to compare a string with an array of chars which are two very different things.. Commented Mar 15, 2013 at 14:58

3 Answers 3

5

Create a new string from the char array and compare.

If(question.equals(new String(answer)){
}

or

If(question.equals(answer.toString()){
}

Having said that, I can't imagine why you are trying to store answers in char[].

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

Comments

1
public boolean equals (Object object)

This method compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.

So first you you need to convert it to first into String using toString method.

For ex:

String string = charArray.toString();

Comments

0

You could use a loop.

boolean equal = true;
for (int i = 0; i < answer.length; i++) {
      if (!question.charAt(i) == answer[i] {
           equal = false;
           break;
      }
 }

I think that should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.