I know this is pretty late but I want to share my solution.
public static void main(String[] args) {
String whatToPrint = "aword";
int strLen = whatToPrint.length(); //var used for auto adjusting the padding
int floors = 8;
for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
for (int k = 1; k < h; k++) {
System.out.print(" ");//padding
}
for (int g = 0; g < f; g++) {
System.out.print(whatToPrint);
}
System.out.println();
}
}
The spaces on the left of the triangle will automatically adjust itself depending on what character or what word you want to print.
if whatToPrint = "x"
and floors = 3
it will print
x
xxx
xxxxx
If there's no automatic adjustment of the spaces, it will look like this (whatToPrint = "xxx"
same floor count)
xxx
xxxxxxxxx
xxxxxxxxxxxxxxx
So I made add a simple code so that it will not happen.
For left half triangle, just change strLen * floors
to strLen * (floors * 2)
and the f +=2
to f++
.
For right half triangle, just remove this loop for (int k = 1; k < h; k++)
or change h
to 0
, if you choose to remove it, don't delete the System.out.print(" ");
.