Reputation: 25
I have a 4x4 2D array which I need to fill with 1's randomly with probability p (from 0.1 to 1.0), or 0 otherwise. I also need to throw an exception if some nonsense value of p is entered e.g. 0 or -1, how can I do this? Thanks!
public GameState(double p) throws Exception
{
int[][] grid = new int[4][4];
Random r = new Random().nextDouble();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (r <= p)
{
//grid[i][j] = ;
}
else
{
//grid[i][j] = ;
}
}
}
}
Upvotes: 0
Views: 419
Reputation: 393
you can see here how to implement Random (which will solve your probability question): Probability in Java
about the exception - In the beginning of the method, just write something like
if (p <0 || p >1) {
throw new Exception()
}
Upvotes: 2