AMAPstudio

User Tools


The Java training online

Back to the table of contents

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

Code of the method Code to be added in main Expected result after execution

Back to the table of contents

solution_of_6._write_a_method_to_create_a_list_of_trees.txt · Last modified: 2021/02/03 16:46 by coligny