milkychance
milkychance

Reputation: 7

Issue converting array to array list

Trying to write a java code for a single row Battleship style game, and when I tried to convert from an array to an ArrayList, the game started returning "miss" no matter what.

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;
    }
}

Upvotes: 0

Views: 73

Answers (1)

WillShackleford
WillShackleford

Reputation: 7008

Change :

int index = locationCells.indexOf(userGuess);

to

int index = locationCells.indexOf(guess);

userGuess is a String which can not possibly be in a list of Integers. guess is an int which can.

Upvotes: 2

Related Questions