Store the return value of the method in ArrayList

advertisements

I am writing a program that creates a game board, and uses a superclass and subclasses to generate the board. Essentially, I want to use an arrayList that stores the values returned back from the methods of the subclasses of Cell. But I cannot figure out how to do it. What I have written in the BoardGame class gives me an error, and I cannot think of another way to do this. 

import java.util.ArrayList;

public class BoardGame {

    private Die theDie;

    BoardGame(){

    }

    void buildBoard(){

        ArrayList<Player> player;

        Cell c = new Cell();

        ArrayList<Cell>cells = new ArrayList<Cell>();

        cells.add(c.landOn());

    }

    void runSimulation(){

    }

     int takeTurn(String n){

         //since we don't know what we are returning yet
         return 0;

    }

     String toString(String n){

         //Since we aren't returning anything yet
         return "Nothing";

     }
}

public class Cell {

    static int landOn(){

        //Since we do not know what we are returning
        return 0;
    }

    public String toString(){

        //Since we do not know what we are returning
        return "Blank";
    }

}

public class Star extends Cell {

    int landOn(){

        //since we do not know what we are returning
        return 5;
    }

    public String toString(){

        //since we do not know what we are returning
        return "Star: +5";
    }

}

public class Lightning extends Cell {

    int landOn(){

        //since we do not know what we are returning
        return -5;
    }

    public String toString(){

        //since we do not know what we are returning
        return "Lightning: -5";
    }

}

public class X extends Cell {

    int landOn(){

        //since we do not know what we are returning
        return -10;
    }

    public String toString(){

        //since we do not know what we are returning
        return "X: -10";
    }

}

public class Smiley extends Cell {

    int landOn(){

        //since we do not know what we are returning
        return 10;
    }

    public String toString(){

        //since we do not know what we are returning
        return "Smiley: +10";
    }

}


Your ArrayList is declared as a Cell The return type for your methods is int. Your ArrayListcannot store anything other then instances of the type Cell

To store all the return types of the methods you need an ArrayList of the type Integer

Using int wont work either as int is a primitive.

Solution:

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