Hello, im trying to get the answers from the secound array but it takes just the last question and answer hers is the code:

search.setOnClickListener(new View.OnClickListener() {

        String[] questions = {
            "http",
            "arp",
            "asd"
        };
        String[] answers = {
            "HyperText Transfer Protocol",
            "Advanced Research Project",
            "asdasdasdasdasdasdasdasd."
        };

        @Override
        public void onClick(View v) {
            String word1 = word.getText().toString();
            for (int i = 0; i < questions.length; i++) {
                for (int j = 0; j < answers.length; j++) {
                    if(word1.equals(questions[i])){
                    description.setText(answers[j]);
                    } else {
                        description.setText("We doesn't find that word");
                    }
                }
            }
        }
    });

why this doesnt work and what should i fix ?

Recommended Answers

All 4 Replies

any responzes please ? :/

not sure what you're trying to do there. why do you need that second loop?
anyway, it takes the last, because you always overwrite the value.
try this:

description.setText("Word not found.");
for ( int i = 0; i < questions.length; i++){
  if ( word1.equals(questions[i])){
    description.setText(answers[i]);
    break;
}

I make it like this:

public void onClick(View v) {
    String Shortword = word.getText().toString();
        for (int i = 0; i < questions.length; i++) {
        if (Shortword.equals(questions[i])) {
            description.setText(answers[i]);
            break;
        } else {
            description.setText("Word not found.");
            return;
        }
    }
}

but now gives me all time "Word not found"

that's ... pretty normal.
let's say Shortword = "arp", which is the second element in your array.
the first value you compare it to is "http". since the equals returns false, the else block is executed.
you set 'Word not found', and through the return statement, you end the method, so the later elements of your array aren't even compared anymore.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.