Southpaw Southpaw - 1 month ago 8
Java Question

Printing a Christmas Tree, using user input and for loops

I need to create a program that lets the user put in what they want the height of the Christmas tree to be. Then it needs to print the Christmas with a trunk attached to it.

I got the Christmas tree part down, but I'm having issues with how I should approach centering the trunk underneath the tree with respect to the tree's actual output.

If someone could point me in the right direction, it would be greatly appreciated.

Thank you in advance.

Here is my code so far:



package Homework8;

import java.util.Scanner;

public class Merry_Christmas2 {
public static void main(String[]args){

System.out.println("Welcome to Christmas Tree!\n");

Scanner input = new Scanner(System.in);
System.out.println("How tall do you want your tree to be?");
int height = input.nextInt();


for(int i = 0; i < height;i++){
for(int j = 0; j< height - i; j++){
System.out.print(" ");
}
for(int k =0; k <= i; k++){
System.out.print("* ");
}
System.out.println();
}
for(int i = 0; i <= height;i++){
for(int j = 0; j >= height;j++){
System.out.print(" ");
}
for(int k = 1; k < 2; k++){
System.out.print("*");
}
System.out.println();
}
input.close();
}
}




Answer

You have an error in your for j loop:

for(int j = 0; j >= height;j++){

Change >= to < and check if it works.