private static int [][] creatMap(int WIDTH){ int[][]mapArr = new int[WIDTH][WIDTH]; int count = 0; while (count < 5) { int ranX = (int) (Math.random() * WIDTH); int ranY = (int) (Math.random() * WIDTH); if (mapArr[ranX][ranY] == 1) {//放地鼠,如果一个地方上有地鼠则不放(也就是值==1,则不放) continue; } mapArr[ranX][ranY] = 1; count++; } }缺少返回语句怎么改
时间: 2024-03-01 11:55:35 浏览: 22
如果你想要返回 `mapArr` 数组,你需要在方法的最后添加 `return mapArr;` 语句,将方法的代码修改如下:
```
private static int[][] createMap(int WIDTH) {
int[][] mapArr = new int[WIDTH][WIDTH];
int count = 0;
while (count < 5) {
int ranX = (int) (Math.random() * WIDTH);
int ranY = (int) (Math.random() * WIDTH);
if (mapArr[ranX][ranY] == 1) {
continue;
}
mapArr[ranX][ranY] = 1;
count++;
}
return mapArr;
}
```
这样,你就可以在其他方法中调用 `createMap` 方法并使用返回的 `mapArr` 数组了。
相关问题
int[][] mapArr == creatMap(WIDTH);为什么报错
这段代码中存在两个问题:
1. 应该使用赋值操作符 "=" 而不是相等操作符 "==",将 "==" 改为 "=" 即可。
2. 代码中的 "creatMap(WIDTH)" 方法未定义,应该先定义该方法或者导入包含该方法的类。
修改后的代码如下:
```
int[][] mapArr = createMap(WIDTH);
```
请注意,我只是根据您提供的信息回答了您的问题,如果您需要更详细的解释或帮助,请提供更多的上下文和代码。
public class Dome10 { public static void main(String[] args) { final int WIDTH =6; int[][] mapArr = new int[WIDTH][WIDTH]; // 初始化地图 for (int i = 0; i < mapArr.length; i++) { for (int j = 0; j < mapArr[i].length; j++) { System.out.print(mapArr[i][j] + " "); } System.out.println(); } int count=0; while (count < 5){ int ranX=(int) Math.random()*WIDTH; int ranY=(int) Math.random()*WIDTH ; if (mapArr[ranX][ranY]==1){ continue; } mapArr[ranX][ranY]=1; count++; } for (int i = 0; i < mapArr.length; i++) { for (int j = 0; j < mapArr[i].length; j++) { System.out.print(mapArr[i][j] + " "); } System.out.println(); } } }哪错了
这段代码没有明显的语法错误,但是有一个逻辑错误。具体来说,`int ranX=(int) Math.random()*WIDTH;` 和 `int ranY=(int) Math.random()*WIDTH ;` 这两行代码没有加上括号,导致它们的计算顺序不一定是我们期望的。正确的代码应该是这样的:
```
int ranX = (int) (Math.random() * WIDTH);
int ranY = (int) (Math.random() * WIDTH);
```
在这个代码中,我们将 `(int) (Math.random() * WIDTH)` 放入括号中,确保先计算随机数的值,再将结果转换为整型。这样可以避免计算顺序错误的问题。