dimanche 31 janvier 2016

Putting a number at random spots in 2D array

I have a 2D Array that has 5 rows and 5 columns. I want it so that at 8 random spots in that 2D array (make it pick a random row and column) to put a char of '1'.

What I did was call the Random class and generate a number between 0 and 4 (for the 5 spots of the array) then I have two for loops that run 8 times (for the 8 random spots I want), one that goes through the row, the other through the column.

This is the code I have so far:

char[][] battleship = new char[5][5];
//I didn't include this but I have a for loop that populates all the rows and columns with a char of '0'
        Random random = new Random();
        int randomNum = random.nextInt(4);

        for (int i = 0; i < 8; i++)
        {
              for (int o = 0; o < 8; o++)
        {

            battleship[randomNum][randomNum] = '1';

        }
        }

The issue I am getting is that instead of it putting the '1' at 8 random spots, it's putting in 5 spots back to back.

How do I correct this?

Here is an example of the output:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0

The '1' isn't in 8 random spots.

Where did I go wrong?




Aucun commentaire:

Enregistrer un commentaire