Hey I have a question I have been trying to figure out for a couple hours now, I need to use nested loops to print the following
-----1-----
----333----
---55555---
--7777777--
-999999999-
This is what I have so far.
public static void Problem6 () {
System.out.println("Problem 6:");
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
for (int j = 1; j <= 9; j += 2) {
System.out.print(j);
}
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
System.out.println();
}
}
This is what it prints
-----13579-----
----13579----
---13579---
--13579--
-13579-
You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:
Which loop prints out the numbers? The 2nd nested for loop.
What does it do?
It prints out j
where j
ranges from 1
to 9
and j
is incremented by 2 each iteration of the loop. In other words, 1, 3, 5, 7, 9
, which is confirmed in your output
What do you want it to do?
Well let's look at the desired output. You want 1
to be printed once on the first first line. You want 3
to be printed three times on the third next line. You want 5
to be printed five times on the fifth next line after that. And so on.
Do you notice a pattern? You want that loop we mentioned above to print the same number (1
, 3
, 5
, ... i
) as the number of times (1
, 3
, 5
, ... i
).
edit Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still 3
three times, 5
five times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.
Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.