2012-04-05 110 views
2

我想制作一个测验应用程序,所以有5个单选按钮,可能的答案是,只有1个是正确的。然后有一个提交按钮,它有一个onClick =“clickMethod”来处理提交。Android:单选按钮无法正常工作的IF语句

我clickMethod看起来是这样的:

public void clickMethod(View v){ 
       RadioGroup group1 = (RadioGroup) findViewById(R.id.radioGroup1); 
       int selected = group1.getCheckedRadioButtonId(); 
       RadioButton button1 = (RadioButton) findViewById(selected); 
       if (button1.getText()=="Right Answer") 
        Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show(); 
       else 
        Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show(); 
    } 

但是我不能得到IF语句的工作不管。如果我尝试使用 “button1.getText()”作为参数来烤面包,它会打印“Right Answer”字符串,但由于某种原因,在IF语句内部它不起作用,而且即使在检查时ELSE也会始终执行正确的答案。

有谁知道可能发生了什么或更好的方法来做到这一点?

回答

2

您应该使用equals字符串的方法比较字符串:

public void clickMethod(View v){ 
    RadioGroup group1 = (RadioGroup) findViewById(R.id.radioGroup1); 
    int selected = group1.getCheckedRadioButtonId(); 
    RadioButton button1 = (RadioButton) findViewById(selected); 
    if ("Right Answer".equals(button1.getText())) { 
     Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show(); 
    } else { 
     Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show(); 
    } 
} 
+0

谢谢,这正是问题所在。 – 2012-04-05 18:41:50

3

您没有正确比较字符串。

当我们必须比较字符串对象 引用时,使用==运算符。如果两个字符串变量指向 内存中的同一对象,则比较返回true。否则,比较返回 错误。请注意,'=='运算符不会比较String对象中存在的 文本的内容。它仅比较2字符串指向的参考文献 。

这里阅读:http://www.javabeginner.com/learn-java/java-string-comparison

+0

谢谢。我也会检查那个网站。 – 2012-04-05 18:42:25

1

在Java中,你不能==比较字符串,你必须使用equals()

if (button1.getText().equals("Right Answer")) 
+0

非常感谢。 – 2012-04-05 18:42:42

1

如果你想比较对象我n Java必须使用equals()方法,而不是==运算符 ..

if (button1.getText().toString().equals("Right Answer")) { 
Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show(); 
} else { 
Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show(); 
}