将数组转换为数组列表

时间:2015-08-16 23:22:31

标签: java

尝试为单行Battleship风格游戏编写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;
    }
}

1 个答案:

答案 0 :(得分:2)

更改:

int index = locationCells.indexOf(userGuess);

int index = locationCells.indexOf(guess);

userGuess是一个String,它不可能在整数列表中。猜是一个可以的int。