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. Here 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 square3.5779789689689...(or whatever you’re referring to), so use theMath.floor()method, which rounds the number inside to the nearest integer. And as @Sanjay explained, generate the numbers separately…Now you have actual integers that you can work with.