-1
我想基於用戶輸入更新int行和int列,但是當我運行我的程序時,我懷疑它是默認的方法外的實例化值,我嘗試更新它們。這裏就是我delcare他們:Java - 更新類中的變量值
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」或其他東西(絕對不是由用戶傳入的整數)。
您可能需要在'start()'方法的'while'循環中爲'acceptShot()'分配返回值,類似'int [] shots = acceptShot();''。 – nickb
你是男人,謝謝! @nickb – broncosaurus