2011-02-13 64 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 + ""); 
}