簡體   English   中英

字符串equals()不起作用

[英]String equals() doesn't work

我已經嘗試修復了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));

現在,我正在讀取文件並將其設置為曲線的文本:

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

而且效果很好。 但你必須鍵入現在所示相同數量curvalte中的EditText。 如果我嘗試對帶有curval EditText中的文本使用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()不能解決問題,我也不知道該怎么做。


也許是因為字符串實際上包含數字嗎?

嘗試打印兩個值並查看它們。 您甚至可能無法從文件中獲取正確的值,或者您可能無法獲取一些奇怪的格式字符,例如“ \\ n”

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

好吧,我發現了問題。 這是資產文件的格式! cp1252編碼已將其修復。

字符串中可能有空格,或者Uper和LowerCase之間有區別。 試試這個版本:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM