我正在创建一个Battleship游戏应用程序来学习OOP,Java。我想要展示一个空海"供玩家参考放置他们的舰队。这是我的Gameboard课程的开始:
public class Gameboard {
private int maxRow = 10;
private int maxCol = 10;
private String[][] gameboard; // Hits and misses
private String[][] fleetboard; // Ship locations
private boolean isHuman = false;
private ArrayList <Ship> myShips;
private ArrayList <Point> myShots;
public Gameboard(boolean isHuman) {
this.isHuman = isHuman;
String[][] gameboard = new String[maxRow][maxCol];
fillArray(gameboard, " ");
String[][] fleetboard = new String[maxRow][maxCol];
fillArray(fleetboard, " ");
}
/*
* Fills null String[][] with spaces, " "
* String[][], String -> void
*/
protected void fillArray(String[][] board, String s) {
// doesn't work TODO
for (String[] row : board) {
Arrays.fill(row, s);
}
// also doesn't work TODO
for(int i = 0; i < maxRow; i++) {
for(int j = 0; j < maxCol; j++) {
board[i][j] = s;
}
}
}
我称之为主要:
myConsole.displayBoard(userBoard.getFleet(), userBoard);
userBoard是Gameboard的一个实例。我的结果是nullpointerexception,因为fleetboard充满了空(我调试并看到了这一点)。
目前的输出是:
0 1 2 3 4 5 6 7 8 9
0 |
我想展示一个充满空间的舰队。 displayBoard方法在fleetboard阵列周围输出一些信息,这样玩家就可以放置船只(例如4号船,1号船,7号船等),类似于RL游戏。
答案 0 :(得分:1)
package com.company;
import java.util.Arrays;
public class Main {
public static void main (String[]args) {
String[][] arrayOfArraysOfSpaces = new String[3][3]; // sample size 3x3
for (int i = 0; i < arrayOfArraysOfSpaces.length; i++) {
Arrays.fill(arrayOfArraysOfSpaces[i], " ");
}
}
}
使用预先构建的方法,遍历每个数组并使用该方法用空格填充它。