2011-02-13 59 views
0

我想將兩個變量從一個屏幕傳遞給另一個。從之前的篩選器中,單擊一個按鈕,1或2並將其傳遞給該篩選器。它也傳遞值2作爲正確的值。我知道他們都在工作,因爲我在下一個屏幕上輸出每個變量。這是代碼。但它始終輸出錯誤。簡單如果聲明

Intent i = getIntent(); 
Bundle b = i.getExtras(); 
String newText = b.getString("PICKED"); 
String correct = b.getString("CORRECT"); 
TextView titles = (TextView)findViewById(R.id.TextView01); 
if(newText == correct){ 
titles.setText("Correct" + newText + " " + correct + ""); 
} 
else{ 
    titles.setText("Wrong" + newText + " " + correct + ""); 
} 
+0

http://stackoverflow.com/questions/513832/how-do-i-compare-strings- in-java – kloffy 2011-02-13 17:06:06

回答

3

因爲您沒有比較字符串。你正在比較是否兩個都指向同一個對象。

比較字符串使用

if(nexText.equals(correct)) 
+0

謝謝,工作就像一個款待。我習慣於PHP。 – Somk 2011-02-13 17:10:04

0
if(newText == correct) 

這將始終是假的。要按字符比較兩個字符串的字符的內容,使用.equals方法:

if(newText.equals(correct)) 

使用==在Java對象意味着你將存儲在這些指針/引用的內存地址的值。由於它們是不同的String對象,它們永遠不會擁有相同的地址。

0

你不比較字符串這樣,重寫代碼這種方式得到完成的事情:

Intent i = getIntent(); 
Bundle b = i.getExtras(); 
String newText = b.getString("PICKED"); 
String correct = b.getString("CORRECT"); 
TextView titles = (TextView)findViewById(R.id.TextView01); 
if(newText.equals(correct)){ 
titles.setText("Correct" + newText + " " + correct + ""); 
} 
else{ 
    titles.setText("Wrong" + newText + " " + correct + ""); 
}