Generating Ships

时间:2018-02-03 10:34:43

标签: java random while-loop

I am trying to create a function that will randomly choose places for computer ships but it can't place them on the same spot or on another player ships.

for board I have a int[5][5] board where 0 means a place is empty 1 is for player ship and 2 is for computer ship. I wrote this but it keeps freezing and crashing android studio.

    boolean wrong = true;
    for(int i = 0; i < 5; i++){

        while (wrong)
        {
            Random rand = new Random();
            int x = rand.nextInt(4);
            int y = rand.nextInt(4);

            if(board[x][y] == 1 || board[x][y] == 2){
                wrong = true;
            }

            else {
                board[x][y] = 2;
                wrong = false;
            }
        }

1 个答案:

答案 0 :(得分:-2)

Note that you have problem with following code:

int x = rand.nextInt(4);
int y = rand.nextInt(4);

nextInt() in these invocations will provide one of these values: 0, 1, 2, 3.

Parameter for that method is not inclusive, and you will never target board[4, y] or board[x, 4] fields in the matrix.