Reputation: 201
I wrote some code that will print a diamond
static void printDiamond(int size) {
for (int i = 0; i < size; i++) {
for (int a = 0; a < (size - (i + 1)); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
for (int i = size-1; i >= 0; i--) {
for (int a = 0; a < (size - (i + 1)); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
}
The issue I'm having with the diamond is that it will print double for whatever I input. So, if the user were to input a 6 for the diamond, it should look like this:
XX
X X
X X
X X
X X
XX
With my code, if the user inputs 5, it prints out the following:
XX
X X
X X
X X
X X
X X
X X
X X
X X
XX
Instead of printing out 5 rows, it printed out 10. If I input 3, it will print out 6 rows instead of 3. It seems that for my diamond, it is outputting the number that it receives from the user, but then prints out that amount times 2. Is there a way I can half the size of what the printDiamond
method outputs so it has the correct number of rows?
Upvotes: 4
Views: 249
Reputation: 522741
I was able to correct your code by tweaking the loop boundary conditions. First, you were printing the top portion of your diamond with a height of size
and you were also printing the bottom potion with a height of size
, for a total height of 2*size
.
The other big problem was that you were not handling odd-numbered inputs, as all diamonds were coming out as even number height. I also corrected this problem. Have a look at the code below.
static void printDiamond(int size) {
for (int i = 0; i < (int)Math.ceil(size/2.0); i++) {
for (int a = 0; a < (int)Math.ceil(size/2.0) - (i + 1); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
for (int i = (int)Math.floor(size/2.0)-1; i >= 0; i--) {
for (int a = 0; a < (int)Math.ceil(size/2.0) - (i + 1); a++) {
System.out.print(" ");
}
System.out.print("X");
for (int b = 0; b < (i * 2); b++) {
System.out.print(" ");
}
System.out.print("X");
System.out.println();
}
}
printDiamond(5);
System.out.print("\n");
printDiamond(6);
Output:
XX
X X
X X
X X
XX
XX
X X
X X
X X
X X
XX
Upvotes: 3