2013-11-29 76 views
-2
public class Basic 
{ 
    public static int numGuess; 
    public int guess; 
    public int numHits = 0; 
    private static int[] ships; 
    private boolean hitShip; 
    public static boolean shipSunk; 
    private int[]board = new int[5]; 
    public Basic() 
    { 
     numGuess = 0; 
     hitShip = false; 
     shipSunk = false; 
    } 

     public static void setShips (int[] loc) 
    { 
     ships = loc; 
    } 

    public int Check(int z) 
    { 
     for(int cell : ships) 
     { 
      if(z == cell) 
      { 
       hitShip = true; 
       System.out.println("\nYou hit an enemy ship!"); 
       numHits++; 
       numGuess++; 
       if(numHits == ships.length) 
       { 
        shipSunk = true; 
        System.out.println("\nYou sunk the enemy ship!"); 
        System.out.println("the number of guesses it took you to sink the ship is " + numGuess/3); 
        break; 
       } 
      } 
      else 
      { 
       System.out.println("You've missed the enemy ship!"); 
      } 
     } 
     return z; 
    } 
} 

所以我一直在爲這個學校的戰列艦項目工作,並且我爲我的遊戲製作了這個一維板。到目前爲止,我認爲我的代碼是正確的,但現在我卡住了。在我的每個循環中,由於它會根據我的船的三個值中的每一個值來檢查我的猜測,因此每次我都會打印三次不同的次數。我試圖讓我的程序打印一下,無論我猜是否每次都打一次船。戰列艦項目問題

import java.util.Scanner; 
import java.util.Random; 
public class BasicTester 
{ 
    public static void main(String[] args) 
    { 
     Basic shipp = new Basic(); //initalizes basic class 
     int ship = (int)(Math.random() * 5); // gives ship a random # between 1 - 5 
     int ship1; 
     int ship2; 
     int guess; 
     if(ship <= 2) 
     { 
      ship1 = ship + 1; 
      ship2 = ship + 2; 
     } 
     else 
     { 
      ship1 = ship - 1; 
      ship2 = ship - 2; 
     } 
     int[] locations = {ship, ship1, ship2};// sets array of locations 
     shipp.setShips(locations); // sets locations to ships in other class 
     Scanner guesss = new Scanner(System.in); // Scanner 
     do 
     { 
      System.out.println("\nTell me where the enemy ship is."); 
      guess = guesss.nextInt(); // gives guess the int from Scanner 
      int resultb = shipp.Check(guess); // puts the int guess through the check method 
     } 
     while(Basic.shipSunk == false); 
    } 
} 
+0

你卡在哪裏?你有什麼嘗試? –

回答

0

而不必你

else 
     { 
      System.out.println("You've missed the enemy ship!"); 
     } 

在循環中,你應該在循環之前設置一個標誌

hitIt = false; 

然後,當你檢查對三「船」,你可以在找到命中時將此標誌設置爲「真」。最後,檢查循環後的標誌。如果它仍然是錯誤的,請打印您的消息。