You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:54:01