我不知道为什么但是我的if / else声明在这里工作不正常。它与给定条件相反。
public class MainActivity extends AppCompatActivity {
private int rand1;
private int rand2;
private int points;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points=0;
pickRandomNumbers();
}
private void pickRandomNumbers()
{
Random randy = new Random();
int rand1 = randy.nextInt(10);
int rand2 = randy.nextInt(10);
Button lbutt = (Button) findViewById(R.id.left_button);
lbutt.setText(Integer.toString(rand1));
Button rbutt = (Button) findViewById(R.id.right_button);
rbutt.setText(Integer.toString(rand2));
}
public void leftButtonClick(View view) {
if (rand1 >= rand2){
points++;
} else {
points--;
}
TextView tv = (TextView) findViewById(R.id.points_fields);
tv.setText("Points: " + points);
pickRandomNumbers();
}
public void rightButtonClick(View view) {
if (rand2 >= rand1){
points++;
} else {
points--;
}
TextView tv = (TextView) findViewById(R.id.points_fields);
tv.setText("Points: " + points);
pickRandomNumbers();
}
}
当rand1大于rand2时应该添加点,当它更小时应该减少点但是它只是继续添加点。
当我将rand1>=rand2
更改为rand1>rand2
时,它只会减少积分。两个按钮功能也是如此。请帮助我理解这一点。
答案 0 :(得分:1)
您在班级顶部声明了两个全局变量rand1
和rand2
。稍后,您再次声明两个具有相同名称的变量。 Java将此视为有效代码,因为前两个可以引用为this.rand1
和this.rand2
。当你真的只想创建它们一次时,你可以创建两次变量。
如果在第二次声明之前删除int
,则应该没问题。
答案 1 :(得分:0)
如果你引用对象变量,请使用'这个'关键字insead创建新变量 你走了:
private void pickRandomNumbers(){
Random randy = new Random();
this.rand1 = randy.nextInt(10);
this.rand2 = randy.nextInt(10);
Button lbutt = (Button) findViewById(R.id.left_button);
lbutt.setText(Integer.toString(rand1));
Button rbutt = (Button) findViewById(R.id.right_button);
rbutt.setText(Integer.toString(rand2));
}
答案 2 :(得分:0)
您在rand1
方法的范围内声明了新的rand2
和pickRandomNumbers
变量。您需要做的是修改已存在的rand变量。
如果您希望rand1和rand2正常工作,请尝试说出this.rand1 = randy.nextInt(10)
。这样,您不是在方法范围内定义新变量,而是定义已经声明的全局变量。
执行此操作后,您的leftButtonClick
方法应该可以正常运行。