vendredi 2 décembre 2016

How to generate random numbers and distribute them randomly to some buttons?

I am rookie in android programming and want to generate some numbers randomly in a specific range. Provided that, the sum of two of them equals a certain number, I wrote the following in onCreate() and onRestart to re-generate them every time the activity starts, but it doesn't work every time:

//i1,i2,i3..... are initialized in the class body as integers

      do {
        i1=r.nextInt((30-1)+1)+1;
        i2=r.nextInt((30-1)+1)+1;
        i3=r.nextInt((30-1)+1)+1;
        i4=r.nextInt((30-1)+1)+1;
        i5=r.nextInt((30-1)+1)+1;
        i6=r.nextInt((30-1)+1)+1;
        i7=r.nextInt((30-1)+1)+1;
        i8=r.nextInt((30-1)+1)+1;
        i9=r.nextInt((30-1)+1)+1;
    }  while (i1+i2!=25);

    String[] str= {String.valueOf(i1),String.valueOf(i2),String.valueOf(i3),
            String.valueOf(i4),String.valueOf(i5),String.valueOf(i6),
            String.valueOf(i7),String.valueOf(i8),String.valueOf(i9)};

    btn1= (Button) findViewById(R.id.btn1);
    btn2= (Button) findViewById(R.id.btn2);
    btn3= (Button) findViewById(R.id.btn3);
    btn4= (Button) findViewById(R.id.btn4);
    btn5= (Button) findViewById(R.id.btn5);
    btn6= (Button) findViewById(R.id.btn6);
    btn7= (Button) findViewById(R.id.btn7);
    btn8= (Button) findViewById(R.id.btn8);
    btn9= (Button) findViewById(R.id.btn9);

    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
    btn3.setOnClickListener(this);
    btn4.setOnClickListener(this);
    btn5.setOnClickListener(this);
    btn6.setOnClickListener(this);
    btn7.setOnClickListener(this);
    btn8.setOnClickListener(this);
    btn9.setOnClickListener(this);

    // this is the code which distribute the numbers randomly to the buttons:
    btn1.setText(str[random.nextInt(str.length)]);
    btn2.setText(str[random.nextInt(str.length)]);
    btn3.setText(str[random.nextInt(str.length)]);
    btn4.setText(str[random.nextInt(str.length)]);
    btn5.setText(str[random.nextInt(str.length)]);
    btn6.setText(str[random.nextInt(str.length)]);
    btn7.setText(str[random.nextInt(str.length)]);
    btn8.setText(str[random.nextInt(str.length)]);
    btn9.setText(str[random.nextInt(str.length)]);

Sometimes there are really two numbers of them whose sum is '25' but sometimes no, and I don't understand the reason. And, I want to know how to generate those numbers without repeating.




Aucun commentaire:

Enregistrer un commentaire