简体   繁体   English

Java 2d数组If语句

[英]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. 我制作了2D数组来显示地图,但我很难制作,因此,如果可以将随机数“ 1”放置在数组中除[0] [0]之外的任何位置,我已经做了很多尝试结果很奇怪。

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. 另一种选择是从1到15中选择一个随机数,然后使用除法和余数。

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. 现在,您在两个维度上都使用了相同的随机数,因此(0,0),(1、1),(2、2)或(3,3)都可以设置为1 ,但是没有其他点。

Choose 2 different random numbers, one for each dimension. 选择2个不同的随机数,每个维度一个。 It's best to create a java.util.Random object, so you can call nextInt(4) to get the range you need. 最好创建一个java.util.Random对象,因此您可以调用nextInt(4)来获取所需的范围。 In a while loop, if both numbers are 0 , choose 2 different random numbers again. while循环中,如果两个数字均为0 ,请再次选择2个不同的随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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