如何在Java二维数组的随机位置插入指定元素
实现方案
你只需要在注释// code to place it in a random position的位置补充随机生成行列索引、给对应位置赋值的逻辑即可,具体代码如下:
// 生成随机行下标,范围0~4 int randomRow = randomPosition.nextInt(world.length); // 生成随机列下标,范围0~4 int randomCol = randomPosition.nextInt(world[0].length); // 给随机位置赋值为目标元素1 world[randomRow][randomCol] = taxi;
补充后完整代码示例
public void StartingLocations(){ int[][] world = new int[5][5]; Random randomPosition = new Random(); int taxi = 1; // 随机放置目标元素的代码 int randomRow = randomPosition.nextInt(world.length); int randomCol = randomPosition.nextInt(world[0].length); world[randomRow][randomCol] = taxi; // 打印二维数组 for(int i=0; i<5; i++){ for(int j=0; j<5; j++){ System.out.printf("%5d",world[i][j]); } System.out.println(); } }
代码说明
Random.nextInt(int bound)方法会返回大于等于0、小于bound的随机整数,刚好匹配二维数组的下标范围(5x5的数组行列下标都是0到4,对应bound为5)- 用
world.length和world[0].length获取行列长度的写法更通用,后续如果修改二维数组的大小也不需要调整随机生成的代码
内容的提问来源于stack exchange,提问作者Wannahelp
相关产品推荐
相关产品推荐

