Issue
I have to print this out using Java and loops.
I've tried to solve it, but I just managed to print out the upper triangle. How should I move on? And my friends said that my code is way too complex for such an easy question.
public class repet {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = i; j < 5; j++) {
System.out.print(".");
}
if (i <= 5) {
for (int k = 1; k <= i*2-1; k++) {
System.out.print(i);
}
}
for (int j = i; j < 5; j++) {
System.out.print(".");
}
System.out.println();
}
}
}
Solution
First of all: no worries about your friends comments - the rule for coders is always:
- do it
- do it correct
- do it better
So you can try to improve on your implementation as soon as it is working. When you want to collect some insights on that, search for "premature optimization".
You implementation is OK so far, what is missing is the rule for how to proceed when the counter i
is going over 5.
For the digits you already have built in an explicit if
statement to check for this, for the dots you relied on the exit condition in the for loops that generate them - you should change this in a way that allows you to decouple the number of digits and dots to print from the counter i
that decides the digit to print:
Assign the number of digits to print to a variable:
int digits;
if (i <= 5) {
digits = i * 2 - 1;
} else {
digits = (10 - i) * 2 - 1;
}
Then also calculate the number of dots depending on the number of digits, not the loop counter i
:
int dots = (9 - digits) / 2;
Now you can simply count from 0 to the precalculated limits in each of your loops and don't need another if for the digits:
for (j = 0; j < dots; j++)
and for (k = 0; k < digits; k++)
Further optimizations depend on your level of Java-knowledge:
- Extract the printing of the dots into a method because you have the same code twice. Use the number of dots as parameter.
- Replace the inner for loops completely with the
String.repeat
method. - Replace the
if
in the calculation ofdigits
with a "ternary operator". - Replace the
if
in the calculation ofdigits
anddots
with a formula that works without the condition, but usesMath.abs()
instead.
Answered By - cyberbrain
Answer Checked By - Candace Johnson (JavaFixing Volunteer)