字符串equals()不起作用

时间:2014-08-15 20:22:49

标签: java android string integer equals

这是我现在试图解决3个小时的问题。 该应用程序如何工作: 我在txt文件中有一个数字列表(在资产中)。我逐行读取该txt文件,并将TextView的文本设置为当前行。现在我必须在EditText中键入相同的数字。但是,如果我比较EditText和当前行,应用程序说它们不一样,尽管它们是。


我的资产中包含不同数字的文件,如下所示:

3
9
8
14
[finish]

稍后将使用[finish]标记,以便我可以完成该应用程序,但现在非常不必要。


我已经定义了以下字符串和视图:

public String curval;
public EditText etds;
public TextView curvalte;

我的onCreate()方法的一部分:

etds = (EditText)findViewById(R.id.editText1);
buttonds = (Button)findViewById(R.id.button1);
curvalte = (TextView)findViewById(R.id.textView2);
try {
    inds = this.getAssets().open(assetname);
} catch (IOException e) {
    e.printStackTrace();
}
readerds = new BufferedReader(new InputStreamReader(inds));

现在我正在从文件中读取并将其设置为curvalte文本:

curval = readerds.readLine();
curvalte.setText(curval);

它运作得很好。 但是,您必须输入EditText中curvalte中显示的相同数字。 如果我尝试在EditText中使用curval对文本使用equals(),它总是说EditText.getText()。toString不等于curval

if(etds.getText().toString().equals(curval.toString()){
    // The code here
}else{
    // This is what I get
    Toast.makeText(getBaseContext(), "Wrong answer!", Toast.LENGTH_LONG).show();
}

即使我输入了正确的答案,我也会觉得这是错误的。 删除.toString()并没有解决它,我也不知道我能尝试什么。


也许是因为字符串实际上包含一个数字?

4 个答案:

答案 0 :(得分:0)

尝试打印两个值并查看它们。您可能甚至没有从文件中获取正确的值,或者您可能获得了一些奇怪的格式化字符,如" \ n"

答案 1 :(得分:0)

尝试使用.trim(),有时这就是问题

if(etds.getText().toString().trim().equals(curval.toString().trim()){
    // The code here
}else{
    // This is what I get
    Toast.makeText(getBaseContext(), "Wrong answer!", Toast.LENGTH_LONG).show();
}

答案 2 :(得分:0)

好吧,我发现了问题。这是资产文件的格式! Cp1252编码修复了它。

答案 3 :(得分:0)

也许你在字符串中有空格或者Uper和LowerCase之间有区别。试试这个版本:

    if(etds.getText().toString().trim().toLowerCase().equals(curval.toString().trim().toLowerCase())){
        Log.i("Yes", "equal");
    } else {
        Log.i("NO", "not equal");
    }