Write a program that produces images of Christmas trees as output. It should have a method with two parameters: one for the number of segments in the tree and one for the height of each segment. For example, the tree shown here on the left has three segments of height 4 and the one on the right has two segments of height 5:
Program:
import java.util.Scanner;
public class CharistmasTreeTest{
// Method to generate the Christmas tree image
public static void generateTree(int segments, int height) {
// Calculate the width of the tree
int width = height * 2 - 1;
// Iterate through each segment
for (int segment = 1; segment <= segments; segment++) {
// Iterate through each row of the segment
for (int row = 1; row <= height; row++) {
// Calculate the number of spaces and asterisks for each row
int numSpaces = height - row;
int numAsterisks = row * 2 - 1;
// Print the spaces
for (int i = 1; i <= numSpaces; i++) {
System.out.print(" ");
}
// Print the asterisks
for (int i = 1; i <= numAsterisks; i++) {
System.out.print("*");
}
// Move to the next line
System.out.println();
}
}
// Print the trunk of the tree
for (int i = 1; i <= segments; i++) {
for (int j = 1; j <= width / 2 - 1; j++) {
System.out.print(" ");
}
System.out.println("| |");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the number of segments and height
System.out.print("Enter the number of segments: ");
int segments = scanner.nextInt();
System.out.print("Enter the height of each segment: ");
int height = scanner.nextInt();
// Generate the Christmas tree
generateTree(segments, height);
scanner.close();
}
}
Executed Output:
Enter the number of segments: 4
Enter the height of each segment: 5
*
***
*****
*******
*********
*
***
*****
*******
*********
*
***
*****
*******
*********
*
***
*****
*******
*********
| |
| |
| |
| |