【发布时间】:2023-03-15 11:20:01
【问题描述】:
我的 xml 中有 2 个文本视图、1 个编辑框和 1 个按钮。
在我的代码中,这一行不起作用:
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
但下一行(else 语句)正在工作,并且在两种情况下(if & else 语句)它都显示 else 函数 toast(“错误”)。
这是我的代码:
public class GameActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
tv.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
tv2.setText(j +"");
int a = Integer.parseInt(tv.getText().toString());
int b = Integer.parseInt(tv2.getText().toString());
int result = a*b;
String str = String.valueOf(result);
EditText txt4 = (EditText) findViewById(R.id.editText1);
String c = txt4.getText().toString();
if(TextUtils.isEmpty(txt4.getText().toString())) {
txt4.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(GameActivity.this, "wrong",Toast.LENGTH_LONG).show();
}
txt4.setText("");
}
});
}
【问题讨论】:
-
所以
c.equals(str)在您期望为真时返回假?您是否调试并检查了c和str的值实际上应该相等吗?如果实际满足条件,您是否检查了Toast.makeText(...)做正确的事情并且其中没有一些硬编码值? -
在
if之前运行Log.e('testing equal',c+":"+str)并在此处发布日志结果。它应该显示类似String1:StringYouThinkIsString1 -
str似乎实际上包含一个数字,您是否尝试将用户输入解析为数字(检查是否首先输入了数字,例如使用简单的正则表达式)并比较数字而不是字符串? -
另一件事:
r1.nextInt((9 - 2) + 1)看起来很奇怪,为什么不简单地r1.nextInt(10 - 3)或只是r1.nextInt(7)? -
在比较之前打印
c, str并检查它们是否相同.....
标签: java android eclipse equals equals-operator