solution_of_6._write_a_method_to_create_a_list_of_trees
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
anddouble ySize
- as it is supposed to build
SpatializedTree
instances, it could be added inSpatializedTree
and bepublic
andstatic
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 injava.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
andy
- to get an int between
0
andn
, userandom.nextInt (n);
- to get a double between
0
andn
, userandom.nextDouble() * n;
- Once the tree built, add it in the list with
list.add(tree);
A possible solution
solution_of_6._write_a_method_to_create_a_list_of_trees.txt · Last modified: 2021/12/13 09:28 by 127.0.0.1