繁体   English   中英

Android:带有单选按钮的 IF 语句不起作用

[英]Android: IF statement with radio buttons not working

我正在尝试制作一个测验应用程序,因此有 5 个带有可能答案的单选按钮,只有 1 个是正确的。 然后是一个提交按钮,它有一个 onClick="clickMethod" 来处理提交。

我的 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()”作为参数敬酒,它会打印“正确答案”字符串,但由于某种原因在 IF 语句中它不起作用,即使我检查正确答案。

有谁知道可能会发生什么或更好的方法吗?

您没有正确比较字符串。

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

阅读此处: http://www.javabeginner.com/learn-java/java-string-comparison

您应该使用equals String 方法进行字符串比较:

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();
    }
}

在 Java 中,您不能将字符串与==进行比较,您必须使用equals()

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

如果你想比较 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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM