Android 简单If语句

Android 简单If语句,android,comparison,instance,Android,Comparison,Instance,我试图将两个变量从一个屏幕传递到另一个屏幕。在上一个屏幕中,单击按钮1或2,它会将该值传递给用户。它还将值2作为正确值传递。当我在下一个屏幕上输出每个变量时,我知道它们都在工作。这是代码。但它总是输出错误 Intent i = getIntent(); Bundle b = i.getExtras(); String newText = b.getString("PICKED"); String correct = b.getString("CORRECT"); TextView titles

我试图将两个变量从一个屏幕传递到另一个屏幕。在上一个屏幕中,单击按钮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 + "");
}

因为您没有比较字符串。如果两者都指向同一对象,则进行比较

比较字符串的用法

if(nexText.equals(correct))

因为您没有比较字符串。如果两者都指向同一对象,则进行比较

比较字符串的用法

if(nexText.equals(correct))
这永远是错误的。要逐个字符比较两个字符串的内容,请使用.equals方法:

if( newText.equals(correct) )
在Java中的对象上使用==意味着您正在比较存储在这些指针/引用中的内存地址的值。因为它们是不同的字符串对象,所以它们永远不会有相同的地址

这永远是错误的。要逐个字符比较两个字符串的内容,请使用.equals方法:

if( newText.equals(correct) )

在Java中的对象上使用==意味着您正在比较存储在这些指针/引用中的内存地址的值。因为它们是不同的字符串对象,所以它们的地址永远不会相同。

如果不以这种方式比较字符串,请以这种方式重写代码以完成任务:

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 + "");
}

您不会以这种方式比较字符串,而是以这种方式重写代码以完成任务:

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 + "");
}