[FIXED] random Strings in ArrayList


I bought Head First Java book, and i am trying to do the exercise sink a startup.

After a while the book introduce ArrayList, and show how to use it in the class and its’ method.

Problem is once i change everything with arraylist, the MAIN doesn’t work, becasue at start i used simple INT, in the array location, now it need array.

How can i change the values of INT into a type that i can put inside the array ?

thx for help, and here the code.

the class with the method:

private ArrayList<String> locationCells;
private int numOfHits = 0;

public void setLocationCells(ArrayList<String> locationCells) 
    this.locationCells = locationCells;

    public String checkYourself(String guess) {
    // creazione stringa miss
        String result = "miss";
        int index = locationCells.indexOf(guess);
        if (index >= 0) {
            if (locationCells.isEmpty()) {
                result = "kill";
                numOfHits ++;
                result = "hit";

        return result;

and here the MAIN:

public static void main(String[] args) {
     java.util.Random randomGenerator = new java.util.Random();
     Scanner scan = new Scanner(System.in);
     StartUpCorretta dot = new StartUpCorretta();

    int manyGuesses = 0;
    boolean isAlive = true;
    int randomNumbers = randomGenerator.nextInt(5) +1;
    int randomNumb = (int) (Math.random() * 5);
    ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};

    while(isAlive) {
        System.out.println("enter a number");
        int guess = scan.nextInt();
        String result = dot.checkYourself(guess);
        manyGuesses ++ ;
        if (result.equals("kill")) {
            isAlive = false;
        System.out.println("you took" + " " + manyGuesses + " " + "guesses");


Seems, you are taking your input from console as int from this statement
int guess = scan.nextInt();

So, my answer is based on your input data type.

Please, changed your arraylist generic type String to Integer
And Secondly, this is not how you can initialized the arraylist

ArrayList<String> location = {randomNumbers,randomNumbers +1,randomNumbers +2};

Correct way to create collection using new operator like this

ArrayList<Integer> location = new ArrayList<>();

and correct way to add element into arraylist like this


Hope, it will work for you.

Answered By – Sawan Meshram

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published