I am creating a game of Battleships using Java and I am having trouble generating 2 random numbers which randomly choose a place on the battleship board. For example, the computer has to randomly choose a space on the board to place the ships (and later to shoot on).
I have created a 2D array:
int rows = 10;
int cols = 10;
char [][] grid;
grid = new char[rows][cols];
And then tried several different ways to get the two random numbers in the array but I cannot get it to work. Her开发者_StackOverflowe is an example of what I have tried:
int randomPos = (char) (Math.random() * (grid[rows][cols] + 1));
Please ask me some questions if this doesn't make sense.
Sean
Math.random()
generates a decimal number. It doesn't make any sense to have square 3.5779789689689...
(or whatever you're referring to), so use the Math.floor()
method, which rounds the number inside to the nearest integer. And as @Sanjay explained, generate the numbers separately...
int row = (int) Math.floor(Math.random() * rows);
int col = (int) Math.floor(Math.random() * cols);
Now you have actual integers that you can work with.
Generate two random numbers separately and use them to index your board. To elaborate:
x = random(max_rows)
y = random(max_cols)
(x, y) -> random location (only if it's not already marked)
In your case, the range of the random number should be between 0 and 9 (inclusive both).
int randomRow = Math.random() * grid.length;
int randomColumn = Math.random() * grid[0].length;
I wouldn't use char as my grid type, but the code above works all the same regardless of the types of in the array.
Try this declare this is an ivar:
Random random = new Random();
//In the method do this:
int randomPos = generator.nextInt(11); //This generates a number between 0 and 10.
精彩评论