我正在使用下面的方法使用数组打印游戏的 map 。当我打印数组时,如何隐藏一些字符(它们没有特定的模式,因为它们是由计算机随机猜测的)?:
public static void print2D(char[][] ocean_map) {
int j = 0;
System.out.print(" ");
for(int i = 0; i < ocean_map.length; i++){
System.out.print(" " + i + " ");
}
System.out.println();
for (char[] row : ocean_map) {
System.out.println(j + "|" + Arrays.toString(row) + "|" + j);
j++;
}
System.out.print(" ");
for(int i = 0; i < ocean_map.length; i++) {
System.out.print(" " + i + " ");
}
System.out.println();
}
最佳答案
您可以编写一个方法来代替Arrays.toString(row)
来处理这个问题。例如
String rowAsString(char[] row) {
// this is the list of characters you want to show
List<Character> whitelist = Arrays.asList('a', 'b', 'c');
StringBuilder sb = new StringBuilder();
for (char ch : row) {
final String toAdd;
if (whitelist.contains(ch)) {
toAdd = ch;
} else {
toAdd = ' ';
}
sb.append(toAdd);
}
return sb.toString();
}
关于java - 在Java中打印数组时跳过一些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60825799/