Reputation: 540
i dont know why but my if/else statement here is not working right. it is working opposite the given condition.
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();
}
}
it should add points when rand1 is greater then rand2 and decrease points when it is smaller but it just keep adding the points.
When I changes rand1>=rand2
to rand1>rand2
it only decrease the points. The same is happening for both of button functions. Kindly help me understand this.
Upvotes: 2
Views: 1401
Reputation: 468
You declare new rand1
and rand2
variables within the scope of the pickRandomNumbers
method. What you need to be doing is modifying the rand variables that already exist.
Try saying this.rand1 = randy.nextInt(10)
, if you want rand1 and rand2 to work properly. That way, you are not defining a new variable within the scope of your method, but rather defining the global variables you have already declared.
Once you do this, your leftButtonClick
method should work properly.
Upvotes: 0
Reputation: 459
You declare two global variables rand1
and rand2
at the top of your class. Later on, you again declare two variables with the same names. Java accepts this as valid code, because the first two can be referenced as this.rand1
and this.rand2
. You create the variables twice, when you really only want to create them once.
If you remove the int
before the second declarations, it should be fine.
Upvotes: 1
Reputation: 6416
If you refer to object variables use 'this' keyword insead of creating new variable Here you go:
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));
}
Upvotes: 0