AMAPstudio

### Sidebar

The Java training online

# Solution: 6. Write a method to create a list of trees

Try to work with the helping elements before looking at the solution…

Helping elements

• the method could be named createTrees()
• it takes 3 parameters: int numberOfTrees, double xSize and double ySize
• as it is supposed to build SpatializedTree instances, it could be added in SpatializedTree and be public and static for a convenient use
• it can be static if it needs only its parameters to be run, which is the case here, it will be called this way: List treeList = SpatializedTree.createTrees (n, xSize, ySize); (list in java.util)
• use an instance of Random to get random int or double values: Random random = new Random ();
• note that random is not directly a number but a random number generator
• create a list to add the trees and to be returned at the end, e.g. with the java.util.ArrayList class
• make a for loop, with numberOfTrees iterations, e.g. for (int i = 0; i < numberOfTrees; i++) {
• set the values for id (e.g. id = i + 1;), age, height, dbh, x and y
• to get an int between 0 and n, use random.nextInt (n);
• to get a double between 0 and n, use random.nextDouble() * n;
• Once the tree built, add it in the list with list.add(tree);

A possible solution