我正在尝试根据用户输入更新int row和int列,但是当我运行我的程序时,我怀疑它是默认为我尝试更新它们的方法之外的实例化值。这是我照顾他们的地方:
public class BattleshipGame {
// Instance variables.
public static Ocean ocean = new Ocean();
public int row;
public int column;
private int[] shots = new int[2];
Scanner scanner = new Scanner(System.in);
然后我尝试用这种方法更新它们:
int[] acceptShot() {
System.out.println("\nDrop a bomb at grid (enter row, a space, then
column):");
int[] shots = new int[2];
shots[0] = scanner.nextInt();
shots[1] = scanner.nextInt();
if (shots[0] > 9 || shots[1] > 9) {
System.out.println("Invalid coordinates.");
acceptShot();
}
System.out.println("You bombed row " + shots[0] + " and column " + shots[1] + ".");
return shots;
}
最终目标是让他们改变这段代码:
void start() {
setUp();
ocean.placeAllShipsRandomly();
ocean.print();
while (!(ocean.isGameOver())) {
acceptShot();
row = shots[0];
column = shots[1];
checkForHit(row, column);
}
endGame();
}
但是在上面的代码中,我强烈怀疑int row和int列被赋予“null”或者其他东西(绝对不是用户传入的整数)。
答案 0 :(得分:0)
这是如何修复的,谢谢@nickb
你可能需要从acceptShot()中分配返回值,比如int [] shots = acceptShot();在start()方法的while循环中。 - nickb