I am not sure if this design was asked by other people.
So this is the design:
-----1-----
----333----
---55555---
--7777777--
-999999999-
And the code I have is this:
for (int i = 1; i <= 9; i = i + 2) {
for (int j = 5 ; j >= i; j--) {
System.out.print("-");
}
for (int j = 1; j <= i; j++) {
System.out.print(+i);
}
for (int j = 5; j >= i; j--) {
System.out.print("-");
}
System.out.println();
}
}
}
But this is my output:
-----1-----
---333---
-55555-
7777777
999999999
EDIT:
I added something on my program:
for (int i = 1; i <= 9; i = i + 2) {
for (int j = 9 ; j >= i; j = j - 2 ) {
System.out.print("-");
}
for (int j = 1; j <= i; j++) {
System.out.print(+i);
}
for (int j = 9; j >= i; j = j - 2) {
System.out.print("-");
}
System.out.println();
And I got it right! Now, my question will be, is there any SIMPLER way of doing this? Because I think what I did was not the real code. But if it is, then thanks anyway!
Thank you :)
1 reply to this topic
#1
Posted 21 November 2011 - 09:53 AM
|
|
|
#2
Posted 21 November 2011 - 04:24 PM
If by easier, you mean less loops.
Pattern:
Pattern:
- Number prints i amount of times per line
- Number of Hyphens are equal on each side, starting at 10, decrementing by 2
final int maxCharPerLine = 11;
int maxHyphensPerLine, currentHyphenAmount, numberCount ;
for(int i = 1; i <= maxCharPerLine; i = i + 2) /* increment in odd amounts starting at 1 */
{
maxHyphensPerLine = maxCharPerLine - i; /* print this amount of hyphens per line */
currentHyphenAmount = 0; /* Zero on side x thus far */
numberCount = maxCharPerLine; /* numberCount unusable at this value */
for (int j = 1; j <= maxCharPerLine ; j++) /* print this amount of chars on every line */
{
if(currentHyphenAmount < maxHyphensPerLine) /* Legal amount for a given side; so print hyphen */
{
System.out.print('-');
currentHyphenAmount++; /* Increment */
/*[COLOR=#ff0000]Key:
Test for max hyphen amount on a given side;
if max amount is reached; stop printing hypens;
switch to printing numbers[/COLOR] */
if (currentHyphenAmount == (maxHyphensPerLine / 2))
{
/* Make the outer if condition fail next time around */
currentHyphenAmount = maxHyphensPerLine + 1;
numberCount = 0; /* Allow numbers to print */
}
}
else
if(numberCount <= i && i != maxCharPerLine) /* If the amount of numbers are within legal range */
{
System.out.print(i);
numberCount++; /* Increment */
if (numberCount == i) /* Enough numbers have been printed;switch to printing hyphens */
{
numberCount++; /* Make the outer loop fail next time around; switch to printing hypens */
currentHyphenAmount = 0; /* Allow hyphens to print */
}
}
}
System.out.println();
}
Perfection of means and confusion of ends seem to characterize our age. Albert Einstein :confused:
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









