I am trying to develop Tic Tac Toe game where player 1 will click one button to put "X" and later player 2(Computer) will put "O" to other buttons randomly on first step.For that I need to create a random number between 0-8 except the one clicked by player 1.
I am using following code to generate random number
Random random=new Random();
int number=random.nextInt(9);
math. random when specified with two values returns a number in the range [m, n]. -1 < 0 < 1 therefore 0 is a valid number in this range. You can't exclude a number, so your best bet would be to do randomise again until the result is not 0.
Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
We can simply use Math. random() method to get random number between 0 to 1. Math. random method returns double value between o(inclusive) to 1(exclusive).
If you want random numbers from 0 to 8 with one value excluded, then there are really 8 possible values, not 9. So generate a random number from 0 to 7 — random.nextInt(8)
— and if the result is greater than or equal to your excluded value, add 1 to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With