2015-08-16 217 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变量可以解析? –