TriangleUtilities.java 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import java.util.*;
  2. public class TriangleUtilities {
  3. /**
  4. * method getRow uses a for loop to create 1 row of stars with a given
  5. * number of stars as the parameter (numberOfStars)
  6. */
  7. public static String getRow(int numberOfStars) {
  8. // Use StringBuilder and a loop
  9. StringBuilder stars = new StringBuilder();
  10. for (int i = 0; i < numberOfStars; i++) {
  11. stars.append("*");
  12. }
  13. return stars.toString();
  14. }
  15. /**
  16. * method getTriangle uses a nested for loop to build the triangle of stars
  17. * with StringBuilder.
  18. *
  19. * Since getSmallTriangle and getLargeTriangle are essentially fixed sizes of
  20. * the star triangles, I call the getTriangle method with the parameter
  21. * "numberOfRows"
  22. */
  23. public static String getTriangle(int numberOfRows) {
  24. StringBuilder stars = new StringBuilder();
  25. for (int i = 1; i <= numberOfRows; i++) {
  26. for (int j = i; j > 0; j--) {
  27. stars.append("*");
  28. }
  29. stars.append("\n");
  30. }
  31. return stars.toString();
  32. }
  33. public static String getSmallTriangle() {
  34. return getTriangle(4);
  35. }
  36. public static String getLargeTriangle() {
  37. return getTriangle(9);
  38. }
  39. }