Danish Khan
Danish Khan

Reputation: 31

How to randomly assign 1 to 10 number on button when execute onCreate Method ? #Android

Could any one help me how to randomly assign 1 to 8 number on button when execute onCreate method ? I have a problem I am creating jigsaw type little game on numbers and I want to assign randomly 1 to 8 numbers on button when app execute onCreate Method.

public void gernate(){
    int min = 1; int max=8;
    Random r = new Random();
    int rand =  r.nextInt(max - min + 1) + min ;

    Button btn1 = (Button)findViewById(R.id.button1);
    Button btn2 = (Button)findViewById(R.id.button2);
    Button btn3 = (Button)findViewById(R.id.button3);
    Button btn4 = (Button)findViewById(R.id.button4);
    Button btn5 = (Button)findViewById(R.id.button5);
    Button btn6 = (Button)findViewById(R.id.button6);
    Button btn7 = (Button)findViewById(R.id.button7);
    Button btn8 = (Button)findViewById(R.id.button8);
    Button btn9 = (Button)findViewById(R.id.button9);

    btn1.setText(rand);
    btn2.setText(rand);


}

MY BAD LOGIC IS ABOVE CAN SOME ONE CORRECT I GET ALL BUTTON AND THEN SET RNDOMLY NUMBERS BY RANDOM FUNCTION BUT WHEN I RUN MY APP .. EMULATOR NOT EXECUTE MY APP

Upvotes: 0

Views: 76

Answers (1)

ShadowGod
ShadowGod

Reputation: 7981

1) For a random integer between 1 and 8 use:

Random r = new Random();
r.nextInt(7) + 1 //gets a random number between 0-7, then adds 1

2) You have to change your rand result to a String before setting the text because setText takes a String -

String rand_as_string = Integer.toString(rand);

or you can do it this way as well:

String stringRand = "" + randNum;

This is the full code, tested and works:

import java.util.Random;

public class MainActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Random generator = new Random();
        int randNum = generator.nextInt(7) + 1;

        Button btn = (Button)findViewById(R.id.button);
        String stringRand = Integer.toString(randNum); // OR use: String stringRand = "" + randNum;
        btn.setText(stringRand);
    }
}

Upvotes: 1

Related Questions