Zul
Zul

Reputation: 3

Reset random generator Android

i am creating an app, that in the class i have this random:

public class Ejemplo extends Activity implements OnClickListener {
 int ran=(int)(1*Math.random()) +1;

and also have this counter

int contador= 0; // this is just to know how many time i won

then i have 2 buttons a1 and a2

and in my onClick

     switch (v.getId()) {
    case R.id.a1:
        if(ran == 1){
            a1.setText("WIN");
            contador= contador + 1;
        }
        else{
            a1.setText("0");
        }
        a1.setClickable(false);
        break;

    case R.id.a2:
        if(ran == 2){
        a2.setText("WIN");
        contador= contador + 1;
        }

        else{
            a2.setText("0");
        }
        a2.setClickable(false);
        break;

so the problem is that when i press the button: New Game the random is going to have the same number of the random, and i cant just call again the activity bc i dont want to reset my counter: contador.

How i can just reset my random, so it doesnt always select the same button?

Upvotes: 0

Views: 1026

Answers (2)

Budius
Budius

Reputation: 39856

just use a Random instead of Math.random it's easier to use, you can have like this:

Random random = new Random(); // random generator

// then inside your onClick this code
if(random.nextBoolean()){
   // win
} else {
   // lose
}

https://developer.android.com/reference/java/util/Random.html

edit:

it's really much simpler than what you trying to do:

public class Ejemplo extends Activity implements OnClickListener {
   Random random = new Random(); // random generator




   // then inside the click listener:
   @Override
   public void onClick(View v) {

   switch (v.getId()) {
     case R.id.a1:
        if(random.nextBoolean()){
           a1.setText("WIN");
           contador= contador + 1;
           gano();
          }
          else{
             a1.setText("0");
          }
          a1.setClickable(false);
          break;

Upvotes: 2

androholic
androholic

Reputation: 3663

Put int ran=(int)(1*Math.random()) +1; in the onClick rather than declaring it as an instance variable in the activity. So everytime a click happens, your ran variable will have a different value.

Upvotes: 0

Related Questions