简体   繁体   中英

Java 2d Array If statement

I made a 2d array to display a map, i'm having trouble making it so that if the random number "1" can be placed anywhere in the array except in [0][0], I've tried a lot of things with strange results.

public static void main (String[] args)
{
    int rnd = (int) (Math.random()*4);
    int[][]map;
    int rows = 4;
    int columns = 4;
    map = new int[rows][columns];
    map[rnd][rnd] = 1;

    for(int i=0; i<map.length; i++){
        for(int j=0; j<map[0].length; j++){    
                System.out.print(map[i][j] + " ");
        }
        System.out.println("");         
    }
    }
}

anyone got a way to do it?

One way is to choose two random numbers and loop until they're not both zero.

Random random = new Random();
int i, j;
do {
    i = random.nextInt(4);
    j = random.nextInt(4);
} while (i == 0 && j == 0);
int[][] map = new int[4][4];
map[i][j] = 1;

An alternative is to choose a random number from 1 to 15 and then use division and remainder.

Random random = new Random();
int i = random.nextInt(15) + 1;
int[][] map = new int[4][4];
map[i/4][i%4] = 1;

It is not obvious what the second version does, so it probably requires a comment to explain it.

Right now, you are using the same random number for both dimensions, so either (0, 0), (1, 1), (2, 2), or (3, 3) could be set to 1 , but no other spots.

Choose 2 different random numbers, one for each dimension. It's best to create a java.util.Random object, so you can call nextInt(4) to get the range you need. In a while loop, if both numbers are 0 , choose 2 different random numbers again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM