Advertisement
Guest User

Forest.java

a guest
Sep 19th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. package lab01;
  2.  
  3. /**
  4. * Forest class
  5. * Models a forest of trees
  6. * @author Chad Humphries
  7. * @version lab01
  8. * Date Created: Sept 14, 2019
  9. */
  10. public class Forest
  11. {
  12. //Variables
  13. private Tree[] trees;
  14.  
  15. /**
  16. * Default constructor
  17. */
  18. public Forest()
  19. {
  20. trees = new Tree[10];
  21. }
  22.  
  23. /**
  24. * Plants a tree
  25. * @param tree Tree to be planted
  26. */
  27. public void plant(Tree tree)
  28. {
  29. for(int i = 0; i < trees.length; i++)
  30. {
  31. if(trees[i] == null)
  32. {
  33. trees[i] = tree;
  34. break;
  35. }
  36. }
  37. }
  38.  
  39. /**
  40. * Determines the amount of trees in the forest
  41. * @return Amount of trees in the forest
  42. */
  43. public int numberOfTrees()
  44. {
  45. int amount = 0;
  46. for(Tree t : trees)
  47. {
  48. if(t != null)
  49. {
  50. amount++;
  51. }
  52. }
  53. return amount;
  54. }
  55.  
  56. /**
  57. * Prints details on all trees in the forest
  58. */
  59. public void showTrees()
  60. {
  61. System.out.println("Trees in forest:");
  62. System.out.println("**********************");
  63. for(Tree t : trees)
  64. {
  65. if(t != null)
  66. {
  67. t.showDetails();
  68. }
  69. }
  70. System.out.println("**********************\n");
  71. }
  72.  
  73. /*
  74. * Prints details on all trees planted in that year
  75. */
  76. void showTreesByYear(int year)
  77. {
  78. System.out.println("Trees planted in: " + year);
  79. System.out.println("**********************");
  80. for(Tree t : trees)
  81. {
  82. if(t != null && t.getYear() == year)
  83. {
  84. t.showDetails();
  85. }
  86. }
  87. System.out.println("**********************\n");
  88. }
  89.  
  90. /**
  91. * Removes all trees planted in that year
  92. * @param year Year of trees to be removed
  93. */
  94. void removeTreesByYear(int year)
  95. {
  96. for(int i = 0; i < trees.length; i++)
  97. {
  98. if(trees[i] != null && trees[i].getYear() == year)
  99. {
  100. trees[i] = null;
  101. }
  102. }
  103. System.out.println("Removed trees planted in: " + year);
  104. }
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement