为什么“等于”不比较字符串和字符串数组?

时间:2018-09-01 16:45:39

标签: java equals

我正在将TextEdit的输入与“ answerList”的答案进行比较。现在我在想:为什么.equals()不比较“ uinput” String?有人可以向我解释一下并在代码中使用它吗?

提前谢谢,祝你有美好的一天!

package ...

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

public TextView view1;
public String uinput;
public EditText edit1;
public TextView score_view;
public int score = 0;

public String[] questionList = {
        "lux, luces",
        "munus, munera",
        "neglere",
};

public String[] answerList = {
        "(dag)licht, dag",
        "taak",
        "verwaarlozen",
};

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

    this.edit1 = findViewById(R.id.edit1);
    this.view1 = findViewById(R.id.view1);
    this.score_view = findViewById(R.id.score_view);
    this.uinput = edit1.getText().toString();
    view1.setText(questionList[0]);
}

    public void check(View view) {
        if (uinput.equals(answerList[0])) {
            edit1.setBackgroundColor(Color.parseColor("#00FF00"));
            score++;
            score_view.setText(score);
        } else {
            edit1.setBackgroundColor(Color.parseColor("#FF0000"));
        }
}

}

2 个答案:

答案 0 :(得分:1)

OP的问题涉及uinput与数组questionList中元素的比较。在check方法中,与uinput进行了比较,但是uinput的值在检查之前没有更新。

public void check(View view) {
    // ADD HERE: update the value of the input
    uinput = edit1.getText().toString();

    if (uinput.equals(answerList[0])) {
        edit1.setBackgroundColor(Color.parseColor("#00FF00"));
        score++;
        score_view.setText(score);
    } else {
        edit1.setBackgroundColor(Color.parseColor("#FF0000"));
    }
}

答案 1 :(得分:0)

删除关键字

......
edit1 = findViewById(R.id.edit1);
view1 = findViewById(R.id.view1);
score_view = findViewById(R.id.score_view);

......

将此添加到OnClick()方法中

uinput = edit1.getText().toString();