2015-08-16 218 views
0

嘗試爲單行戰列艦式遊戲編寫java代碼,並且當我試圖從數組轉換爲ArrayList時,遊戲無論如何都開始返回「miss」。將數組轉換爲數組列表

public class SimpleDotComGame { 
    public static void main(String[] args) { 
     int numofGuess = 0; 
     Scanner sc = new Scanner(System.in); 
     SimpleDotCom dot = new SimpleDotCom(); 
     int ranNum = (int) (Math.random() * 5); 
     ArrayList<Integer> locations = new ArrayList<Integer>(); 
     locations.add(ranNum); 
     locations.add(ranNum + 1); 
     locations.add(ranNum + 2); 
     dot.setLocationCells(locations); //think like you're running a 
      // separate program with parameters to set cells as "locations" 
     boolean isAlive = true; 
     while (isAlive == true) { 
      System.out.println("Enter a number"); 
      String userGuess = sc.next(); 
      String result = dot.checkYourself(userGuess); //run program to 
       // check if cells were hit by userGuess 
      numofGuess++; 
      if (result.equals("kill")) { 
       isAlive = false; 
       System.out.println("You took " + numofGuess + " guesses"); 
      } 
     } 
     sc.close(); 
    } 
} 
public class SimpleDotCom { 
    int numofHits = 0; 
    ArrayList<Integer> locationCells; 
    public void setLocationCells(ArrayList<Integer> locations) { //locations 
      // variable described array so we must define it as array now 
     locationCells = locations; 
    } 
    public String checkYourself(String userGuess) { //check using parameter userGuess 
     int guess = Integer.parseInt(userGuess); 
     String result = "miss"; 
     int index = locationCells.indexOf(userGuess); 
     if (index >= 0) { 
      locationCells.remove(index); 
      if (locationCells.isEmpty()) { 
       result = "kill"; 
      } else { 
       result = "hit"; 
      } 
     } 
     System.out.println(result); 
     return result; 
    } 
} 
+0

TL; DR請提供相關代碼以檢測問題。 –

+1

當你問你的問題時,文本區域右側有一個大的橙色**如何格式化**框,其中包含有用的信息。還有一個格式化輔助工具的整個工具欄。和一個** [?] **按鈕提供格式幫助。 *和*預覽區域位於文本區域和發佈您的問題按鈕之間(以便您必須掃描過去以查找按鈕),以顯示發佈後您的帖子的樣子。明確你的帖子,並證明你花時間這樣做,提高你獲得良好答案的機會。 –

+0

@LuiggiMendoza,我對此很新,我不確定你在問什麼。我很抱歉,只是想學習。 –

回答

2

變化:

int index = locationCells.indexOf(userGuess); 

int index = locationCells.indexOf(guess); 

userGuess是不可能在一列整數的String。猜測是一個int可以。

+0

完美!我們正在運行。謝謝! –

+0

@ L.Seymour如果您使用了'int' /'Integer'的適當參數類型,而不是假裝'String'是一個數字,則可以避免這種情況。用你的輸入解析它,然後傳遞正確的數據類型。 – chrylis

+0

@chrylis對不起,我可能不明白。你的意思是我應該在SimpleDotCom類中設置它之前解析我的userGuess,還是有一個額外的String變量可以解析? –