如何正确比较Android中的字符串?

时间:2017-12-03 23:15:21

标签: java android

我在android中制作anagramm应用程序。我有一些问题,我有按钮文字" A"," B"," C"例如。我的代码生成字符串" ABC"和我的ans [i] =" ABC"。但是当我比较它们时,它会让我失意。请帮助。

有代码示例,我有

的问题

if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();

public class MainActivity extends AppCompatActivity {
public List<Button> btns;
public List<String> ans;
String word = "";
String checkStr;
EditText text;
private static final int[] btn_id = {
        R.id.btn1,
        R.id.btn2,
        R.id.btn3,
        R.id.btn4,
        R.id.btn5,
        R.id.btn6,
        R.id.btn7,
        R.id.btn8
};

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

    btns = new ArrayList<Button>();
    ans = new ArrayList<String>();
    text = findViewById(R.id.txt);
    text.setEnabled(false);
    fillAnswers();

    for (int i = 0; i < btn_id.length; i++){
        Button b = findViewById(btn_id[i]);
        btns.add(b);
    }
}

public void fillAnswers(){
    ans.add("ERATO");
    ans.add("MARI");
    ans.add("AIR");
}

public void onClick(View v){
    Button b = (Button)v;
    char str = b.getText().charAt(0);
    addToString(str);
    text.setText(word);
    b.setEnabled(false);
   // Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
}

public void okClick(View v){

    //Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
    if (word == "ERATO") Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();
  /*  for (int i = 0; i < 3; i++){
       // Toast.makeText(this, word, Toast.LENGTH_SHORT).show();

        if (checkStr == ans.get(i)){
            Toast.makeText(this, word, Toast.LENGTH_SHORT).show();
        }
    }*/

    word = "";
    text.setText(word);
    for (int i = 0; i < btn_id.length; i++){
        Button b = findViewById(btn_id[i]);
        b.setEnabled(true);
    }
}

public void addToString(char s){
    word += s;
}

}

1 个答案:

答案 0 :(得分:0)

您必须将字符串值与等于

进行比较

ans[i].equals("ABC");

或者

if (word.equals("ERATO")) Toast.makeText(this, ans.get(0), Toast.LENGTH_SHORT).show();