YouYour code is not good, because you have a lot of duplicate lines, you create a lot of strings during executethe execution of your loop ( because strings are imutableimmutable, +
creates a new string object). You have a lot of if statmentsstatements which have to be evaluated and some other things.
An alternative solution is:
public static void main(String[] args) {
// Algorithm 1
String o = null;
for (int i = 0; i < 10; i++) {
String x = StringUtils.repeat("X", i+1);
o =StringUtils.repeat("0", 9-i);
System.out.println(x+o);
}
}
StringUtils.repeat
is a helper method, which will print a character n times.
So I create a string with n times a X
and then I do it same with o for the rest and concatenate it for output.
The solution makes your code shorter, more readable, and it uses well tested functions from third party distributor. Why invent the wheel again?
For this solution you Needneed to add the commons-lang3 library to your build/classpath.