This is an exercise for uni I've been working on but I've been stuck on just one last little problem with the output and I just can't find out why.
Goal: User inputs height of tree. It gets printed in the following format:
E.g height 4
4| * |5=2+1+2 (width = 2 spaces+ 1 char + 2 spaces)
3| *** |5=1+3+1
2|*****|5=0+5+0
1| *** |5=1+3+1
Note: The Root is always 3 characters long and should be 1/4th of the height (round off)
Here's my problem: It works fine for every input <8. First I was looking at the wrong place because I feel like it had something to do with the number itself. But 8 is the first height where the root is 2 lines instead of one. (8 * 1/4 = 2) Regardless I could not find a solution (not even a bad one).
I hope my code is readable, I tried to remove everything unnecessary and change the variables to English ones.
My assignment is basically done, it's just this minor detail I cant get a grip on. It's not like I'm asking anyone to do my homework for me; there's on learning in that I agree.
Here's my output for height (works fine)
7| * |11=5+1+5
6| *** |11=4+3+4
5| ***** |11=3+5+3
4| ******* |11=2+7+2
3| ********* |11=1+9+1
2|***********|11=0+11+0
1| *** |11=4+3+4
For anything bigger than 8, e.G 8 I get the following problem in the Root Lines of the tree:
8| * |11=5+1+5
7| *** |11=4+3+4
6| ***** |11=3+5+3
5| ******* |11=2+7+2
4| ********* |11=1+9+1
3| *********** |11=0+11+0
2| *** |11=4+3+4 <--- amount of spaces is still correct but my formating got butchered as you can see, line 3 no longer touches the edges (|), its shifted
1| *** |11=4+3+4
Here's my code:
import java.util.Scanner;
public class SchleifenTestat
{
public static void main(String[] args)
{
Scanner read = new Scanner(System.in);
System.out.print("Enter height:");
int height= read.nextInt();
int heightOutput= height;
int root = (int)(height*0.25F);
int width= ((height- root) * 2) -1; //Amount of chars in the widest tree line
int spaces = (width- 1); //Amount of spaces line 1
int charCount = 1;
int tree = (height- root);
for(int i = 0; i < tree; i++)
{
if(heightOutput<10)
{
System.out.print(" "); //To stay in format with heights <9
}
System.out.print(heightOutput+"|");
heightOutput--;
for(int j=0; j<= height- i -3 ;j++)
{
System.out.print(" ");
}
for(int k=0; k < i*2 + 1; k++ )
{
System.out.print("*");
}
for(int j=0; j<=(height- i - 3);j++) //5 = 2 + * + 2
{
System.out.print(" ");
}
System.out.print("|" + width+ "=" + (spaces/2) + "+" + charCount+ "+" + (spaces/2));
System.out.println();
charCount+=2;
spaces -=2;
}
for(int i = heightOutput; heightOutput> 0; heightOutput--)
{
System.out.print(" " + heightOutput + "|");
for(int j = 0; j<((width-3)/2);j++)
{
System.out.print(" "); //Spaces left side
}
System.out.print("***"); //Root
for(int j = 0; j<((width-3)/2);j++)
{
System.out.print(" "); //Spaces right side
}
System.out.print("|" + width+ "=" + ((width-3 )/2) + "+" + "3" + "+" + ((width- 3)/2));
System.out.println("");
}
}
}