2014-11-02 11 views
0

我正在尋找在我的java項目中顯示命中和小姐。基本上,我輸入一個數字,該程序要麼命中或錯過。如果它命中,它會顯示一個y,並且如果它錯過了x。根據我在代碼中測試的結果,它可以工作,輸出結果是「Hit」或「Try again」,但它不會顯示x或y。在數組Java中顯示命中和小姐

public static void displayRiver(int [] river, boolean showShip) 
{ 
    System.out.println(); 
    System.out.print("|"); 
    for (int val : river) { 
     switch (val) { 
     case -1: // No Ship 
      System.out.print("x"); 
      break; 
     case 0: // Unknown 
      System.out.print(" "); 
      break; 
     case 1: // Ship Found 
     System.out.print("Y"); 
      break; 
     }//switch 
     System.out.print("|"); 
    }//for 


} 

public static void main (String [] args) 
{ 
    int userInput; 
    int length = promptForInt("Enter the length of the river"); 
    int riverLength[] = new int[length]; 
    boolean showShip = false; 
    displayRiver(riverLength, showShip); 
    int randomShipLocation = new Random().nextInt(length); 
    int val; 


    while(! showShip) 
    { 
     val = promptForInt("\n" + "Guess again. "); 
     displayRiver(riverLength, showShip); 

     if(userInput == randomShipLocation) 
     { 
      System.out.println("\n" +" BOOM!"); 
      showShip = true; 
      displayRiver(riverLength, showShip); 
     } 
     else if(userInput != randomShipLocation) 
       System.out.print(val); 

    } 

} 
+0

我不明白你爲什麼要在案例1中對'displayRiver'進行遞歸調用。 – Henry 2014-11-02 08:47:32

+0

抱歉只是改變了它應該是System.out.print(「Y」); – Zinconium 2014-11-02 08:50:13

回答

1

傳遞給displayRiver數組只包含零,因爲你永遠不更改其默認值。

因此您的switch語句總是到達部分顯示空的空間:

case 0: // Unknown 
     System.out.print(" "); 
     break; 

你應該分配1-1基於用戶輸入數組的相關位置。

它看起來像在main方法的循環應該是:

while(!showShip) 
{ 
    val = promptForInt("\n" + "Guess again. "); 
    if(val == randomShipLocation) // val, instead of userInput 
    { 
     System.out.println("\n" +" BOOM!"); 
     showShip = true; 
     riverLength[val] = 1; // mark a hit 
    } 
    else { 
     riverLength[val] = -1; // mark a miss 
    } 
    displayRiver(riverLength, showShip); 
} 

這裏假設你的promptForInt方法驗證輸入(以確保它是數組的範圍內)。