我开发了一个在java中打印钻石的代码。代码使用*和“o”打印钻石,代码为:
System.out.println("Diamond Height: " + DIAMOND_SIZE);
System.out.println("Output for: For Loop");
int noOfRows = DIAMOND_SIZE;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
//Initializing row with 1
int row = 1;
//Printing upper half of the diamond
for (int i = midRow; i > 0; i--)
{
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
for (int j = 1; j <= row; j++) {
System.out.print("* ");
}
System.out.println();
//Incrementing the row
row++;
}
//Printing lower half of the diamond
for (int i = 0; i <= midRow; i++) {
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
int mid = (row+1) / 2;
for (int j = row; j > 0; j--) {
if(i==0 && j==mid) {
System.out.print("o ");
}
else {
System.out.print("* ");
}
}
System.out.println();
//Decrementing the row
row--;
}
}
我从中得到的结果是:
钻石高度:5
*
* *
* o *
* *
*
Diamond Height: 3
*
* o
*
但我试图得到以下结果:
Diamond Height: 5
*
* * *
* * o * *
* * *
*
Diamond Height: 3
*
* o *
*
What am I doing wrong? I have tried several things but nothing seems to help, Please help.
答案 0 :(得分:1)
您可以在打印钻石的下半部分时修改内循环逻辑。
//Printing j *'s at the end of each row
int mid = (row+1) / 2;
for (int j = row; j > 0; j--)
{
if(i==0 && j==mid) System.out.print("o ");
else System.out.print("* ");
}