Mher Harutyunyan Mher Harutyunyan - 7 months ago 57
Java Question

Draw a Java christmas tree with tabs and asteriks

I need to draw a java xmas tree with given n numbers of rows, but not how it is commonly being drawn like this:

*
***
*****
*******


but like this, with seperation tabs:

*
* *
* * *
* * * *


The code I have so far is this:

public static void main(String[] args) {
int i =5;
for(;i!=0;i--) {
for(int j=0; j!=i; j++);
System.out.print("\t\t*");


I have Finally wrote the code by myself:

int x = 5;
for(int i=1; i<=x; i++)
{
for (int k=0; k<x-i; k++)
{
System.out.print("\t");
}
for (int j=0; j<i; j++)
{

System.out.print( "\t*\t" );
}
System.out.println("");
}

}

}

PSD PSD
Answer

This lines up the stars in rows

public static void main(String[] args)
{

    int n = 6;
    int i = 0;
    int pad = 7;
    while (i < n) 
    {

        String star = new String(new char[1 + i *2]).replace("\0", "*\t");
        String space = new String(new char[1 + pad]).replace("\0", "\t");
        System.out.printf(space + star + "\n");
        ++i;
        --pad;
    }

}

EDIT This alternates them as per your demo

public static void main(String[] args)
{
    final int it = 5;
    int pad = it;
    int i = 0;
    String space;
    while (i < it) {
        String star = new String(new char[i + 1]).replace("\0", "*\t\t");

        space = new String(new char[pad]).replace("\0", "\t");

        System.out.printf(space + star + "\n");
        ++i;

        --pad;

    }

}

done with for loops

public static void main(String[] args)
{
    //final int it = 5;
    int size;
    size = 5;

    for( int i = 1;  i < size; ++i)
    {
        String star = "";
        for (int p = size; p > i; --p)
        {
            star += "\t";
        }
        for (int j = 0; j < i; ++j)
        {
            star += "*\t\t";
        }

        System.out.println(star);


    }

}

another solution using only 2 loops

public static void main(String[] args)
{
    //final int it = 5;
    int size;
    size = 5;
    List<String> pad = new ArrayList<String>();
    pad.addAll(Arrays.asList("\t","\t","\t","\t","\t"));
    for( int i = 1;  i < size; ++i)
    {
        String star = "";
        //Pattern p = Pattern.compile("([)|(,)|(])");
        star += pad.toString().replaceAll("\\[|\\]|,", "");
        for (int j = 0; j < i; ++j)
        {
            star += "*\t\t";
        }
        pad.remove(pad.size()-1);
        System.out.println(star);

    }

}
Comments