尝试为单行战列舰式游戏编写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,我对此很新,我不确定你在问什么。我很抱歉,只是想学习。 –