2013-07-26 78 views
-6

我不確定爲什麼我的字符串比較失敗。字符串比較失敗Java

我有一個TextView,我正在更新,因爲用戶點擊一個按鈕。該按鈕的字母出現在TextView中。該部分起作用。

我的TextView上有一個TextWatcher,它使用afterTextChanged(Editable arg0)進行偵聽,發送TextView和另一個字符串進行比較。如果比較結果爲真,則將其發送給另一個方法。但是,無論我如何比較它們,它總是失敗。

這是我曾嘗試:

public void checkText(String textView, String wordVar){ 

    Log.d("checkText","Got the word " + textView.toString() + ". Checking against " + wordVar.toString()); //debug log to compare string values by printing them 
    if(textView.toString().equals(wordVar.toString())){ 
     Log.d("Match","Matches, changing word"); //debug log to notify me when they match 
     try { 
      newWord(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

我也嘗試過其他的變化,比如textView.equals(wordVar)textView.toString() == wordVar.toString()但niether這些工作。

如何比較字符串並讓它返回true?

編輯:公平足夠。下面的LogCat。

這裏是我的文字聽衆:

textView.addTextChangedListener(new TextWatcher(){ 

    @Override 
    public void afterTextChanged(Editable arg0) { 
     check.checkWord(textView.getText().toString(), wordVar); 
    } 

    @Override 
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) { 
     // TODO Auto-generated method stub 
    } 

    @Override 
    public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) { } 
}); 

logcat的輸出:

07-26 21:42:20.398: D/Got(1058): Got the word B. Checking against Begin  
07-26 21:42:21.361: D/Got(1058): Got the word Be. Checking against Begin  
07-26 21:42:23.378: D/Got(1058): Got the word Beg. Checking against Begin 
07-26 21:42:24.979: D/Got(1058): Got the word Begi. Checking against Begin  
07-26 21:42:25.828: D/Got(1058): Got the word Begin. Checking against Begin  

所以他們都過來作爲一個字符串,但我覺得我已經嘗試了對象之間的可用每個比較樣式和字符串,甚至當它們在調試輸出中匹配時,if語句不會被觸發。或者如果是,它就會失敗。

+0

不要忘記,字符串比較區分大小寫 – MadProgrammer

+0

是否有任何前導或後續空格字符?如果是這樣,請修剪()他們。 – rgettman

+0

那麼,Log.d()調用記錄的兩個值是什麼?你爲什麼要在String上調用toString()?爲什麼不在調用時調用wordVar.toString()。toString()。toString()。toString()? –

回答

3

當調試會話顯示它時,其中一個變量的尾部空間被比較。

這裏的東西,可以幫助現貨蝽象這樣的列表:

  • 使用調試器
  • 添加日誌記錄痕跡檢查值的代碼,閱讀
  • 由環繞值分隔符:Log.d("|" + value + "|");現貨尾隨空格
  • 還記錄了字符串的長度
  • 如果它們確實看起來相同但不相等,循環遍歷它們的字符並打印它們整數值。有些字符以相同的方式打印,但不一樣(例如不可破壞的空格和空格)
1

首先,你在參數Strings,所以不要使用toString()方法對他們。

它是如此簡單,這是沒有錯:

if(textView.equals(wordVar))

凡是是怎麼了?是別的地方在你的代碼(區分大小寫字符串,不正確的字符串,開頭或結尾的空格等。 )。