2016-12-14 9 views
-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行とint列が "null"または何か(ユーザーが渡した整数ではない)が割り当てられていると思われます。これは、それが固定された方法です

+0

あなたの 'start()'メソッドの 'while'ループにある' int [] shots = acceptShot(); 'のような' acceptShot() 'の戻り値を割り当てる必要があるかもしれません。 – nickb

+0

あなたは男です、ありがとう! @nickb – broncosaurus

答えて

0

、おかげで

@nickbおそらくacceptShot()からの戻り値を割り当てる必要があり、[] int型のような何かショット= acceptShot();あなたのstart()メソッドのwhileループで。 -nickb

関連する問題