嘗試爲單行戰列艦式遊戲編寫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;
}
}
TL; DR請提供相關代碼以檢測問題。 –
當你問你的問題時,文本區域右側有一個大的橙色**如何格式化**框,其中包含有用的信息。還有一個格式化輔助工具的整個工具欄。和一個** [?] **按鈕提供格式幫助。 *和*預覽區域位於文本區域和發佈您的問題按鈕之間(以便您必須掃描過去以查找按鈕),以顯示發佈後您的帖子的樣子。明確你的帖子,並證明你花時間這樣做,提高你獲得良好答案的機會。 –
@LuiggiMendoza,我對此很新,我不確定你在問什麼。我很抱歉,只是想學習。 –