简体   繁体   中英

String equals() doesn't work

This is a problem I've been trying to fix for 3 hours now. How the app works: I've got a list of numbers in a txt file (in assets). I'm reading that txt file line by line and I set the text of a TextView to the current line. Now I have to type the same number in an EditText. But if I compare the EditText and the current line, the app says they are not the same, although they are.


I've got a file in assets with different numbers, like this:

3
9
8
14
[finish]

The [finish] tag will be used later so I can finish the application, but is pretty unnecessary now.


I've defined the following strings and views:

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

A part of my onCreate() method:

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));

Now I'm reading from the file and setting it as text of curvalte:

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

And it works just fine. But then you have to type the same number that is now shown in curvalte in the EditText. If I try to use equals() on the text in EditText with curval , it always says that EditText.getText().toString doesn't equal 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();
}

Even if I enter the correct answer, I get that toast saying it's wrong. Removing the .toString() didn't fix it and I've got no idea what I could try.


Maybe it's because of the string that actually contains a number?

Try printing both of the values out and looking at them. You may not even be getting the right values from the file or perhaps your getting some weird formatting characters like "\\n"

Try this with .trim(), sometimes that is the issue

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();
}

Alright, I found the problem. It was the formatting of the assets file! Cp1252 encoding fixed it.

Maybe you have spaces in the string or the difference between Uper and LowerCase. Try this version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM