java - 替换打印语句中的元素
问题描述
所以我得到了这个 String 2Dimensional 数组,它打印出一个 playGround :
private final int rowX = 10;
private final int colY = 10;
private final String[][] playGroundArray = new String[rowX][colY];
然后我在我的 playGroundArray(一个字符数组)中添加了一个循环到 10 个随机位置。
mines[0] = "*";
for (int i = 0; i < numberOfMines; i++) {
getPlayGroundArray()[random.nextInt(playGroundArray.length - 2) + 1][random.nextInt(playGroundArray.length - 2) + 1] = Arrays.deepToString(mines);
}
这样一切正常。
现在我打印出来。我明白了:
[[ , 0, 1, 2, 3, 4, 5, 6, 7, ], [0, [*], +, [*], +, +, +, +, [*], ], [1, +, +, +, +, +, +, +, +, ], [2, +, +, +, [*], +, +, +, [*], ], [3, +, +, +, [*], +, +, +, +, ], [4, +, [*], +, +, +, +, +, +, ], [5, +, [*], +, +, +, +, +, +, ], [6, +, +, +, +, +, +, +, +, ], [7, +, +, +, +, +, +, +, +, ], [ , , , , , , , , , ]]
我现在尝试使用 .replace 方法来构建我的 playGround,使它看起来像一个 playGround:
System.out.println(Arrays.deepToString(playGround.getPlayGroundArray())
.replace("[[", " ")
.replace("]]", " \n")
.replace("], [", " \n")
.replace("]", " ")
.replace(",", " ")
.replace("[", " "));
不是我想要的:P
0 1 2 3 4 5 6 7
0 + + + + + *
* +
1 + * + + + + + +
2 * + + + + + + +
3 + * + + + + + +
4 + * + + + + * +
5 + + + + + + + *
6 + + + + + + + +
7 + + * + + + + +
所以结果应该是这样的
0 1 2 3 4 5 6 7
0 + * * + + + + +
1 + + + + * + + +
2 + + * + + + + *
3 * + + + + + + +
4 + + * + + * * +
5 + + + + + + + +
6 + + + + + + * +
7 + + + + + + + +
我最接近的是上面的代码。是否有其他解决方案,因为我尝试了很多方法,但是它们的数组大括号是相同的,所以你不能在不更改字符串数组的大括号的情况下替换字符数组大括号。在每 10 个元素之后,它应该换行。
谢谢你的帮助 :)
解决方案
您不应该使用字符串来表示游乐场 - 使用布尔值会更容易,并且不在枚举本身中包含坐标:
import java.util.*;
public class Playground {
private boolean mines[][];
private int rows;
private int cols;
public Playground(int rows, int cols, int mineCount) {
this.rows = rows; this.cols = cols;
mines = new boolean[rows][cols];
Random rng = new Random();
while (mineCount > 0) {
int r = rng.nextInt(rows);
int c = rng.nextInt(cols);
if ( ! hasMine(r, c)) { // retries placement if mine already there
mines[r][c] = true;
mineCount --;
}
}
}
boolean hasMine(int row, int col) {
return mines[row][col];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(" "); // starts with 3 spaces
for (int c=0; c<cols; c++) {
sb.append(String.format("%3d", c)); // left-pads a number with spaces
}
for (int r=0; r<rows; r++) {
sb.append(String.format("\n%3d", r));
for (int c=0; c<cols; c++) {
sb.append(String.format("%3s", (hasMine(r, c) ? "*" : "+")));
}
}
return sb.append("\n").toString();
}
public static void main(String ... args) {
System.out.println(new Playground(10, 10, 10));
}
}
推荐阅读
- python - 货币转换数据框 - 跳过列
- c# - 如何在 ReactiveUI 中手动重新验证 ValidationContext 的验证?
- html - 拉伸一个元素的高度,但不拉伸另一个元素
- python - 消息:元素点击被拦截:元素...在点 (657, 594) 处不可点击。其他元素会收到 Selenium 的点击
- python - Python Scrapy - 解析最近更新日期的 URL 内容
- r - 在不丢失起始值的情况下逐月计算生存率
- javascript - JavaScript 如何选择主视图
- python - 如何使用动态长度分割字符串?
- c - 释放哈希表时内存泄漏 C
- javascript - 如何在 React 中创建一个仅允许数字或空值的文本框,从而触发移动设备上的数字键盘?