Reputation: 183
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("");
}
}
}
Upvotes: 2
Views: 900
Reputation: 64
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);
}
}
Upvotes: 2
Reputation: 71
If you are thinking of drawing a Christmas tree according to the number of rows, you might be after a Java program as such:
int rows = 5;
int i = ((rows-1)*2) + 1;
String pattern = "";
for(int j = 0; j <= (i/2); j++) {
String spaces = "";
for (int k = 0; k < ((i/2)-j); k++) {
spaces += " ";
}
pattern += spaces;
for (int k = 0; k < (i-(((i/2)-j)*2)); k++) {
pattern += "*";
}
pattern += spaces+"\n";
}
System.out.println(pattern);
where you adjust the variable rows to adjust the height of the Christmas tree. I used spaces to indent the tree, tab can be used with relative adjustment in width. Of course the best way is to use printf but this is probably the most straight forward way in creating the Christmas tree you shown within your first block.
Upvotes: 1