我正在创建仅使用Do while循环打印钻石的代码,我有以下代码:
public static void diamond3() {
System.out.println("Output for: Do while Loop");
int noOfRows = DIAMOND_SIZE;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
//Initializing row with 1
int row = 1;
int i = midRow;
do {
//Printing i spaces at the beginning of each row
int j = 1;
do {
System.out.print(" ");
j++;
}
while (j <= i);
//Printing j *'s at the end of each row
j = 1;
do {
System.out.print("* ");
j++;
}
while (j <= row);
System.out.println();
//Incrementing the row
row++;
i--;
}
while (i > 0);
i = 0;
do {
//Printing i spaces at the beginning of each row
int j = 1;
do {
System.out.print(" ");
j++;
}
while (j <= i);
//Printing j *'s at the end of each row
int mid = (row+1)/2;
j = row;
do {
if(i==0 && j==mid)
System.out.print("o ");
else
System.out.print("* ");
j--;
}
while (j > 0);
System.out.println();
//Decrementing the row
row--;
i++;
}
while(i <= midRow);
}
我的意思是获得钻石形状,但我得到以下形状:
*
* *
* o *
* *
*
预期的出现是:
*
* * *
* * o * *
* * *
*
有人可以帮我找出错误的地方。我已经多次检查了代码,但无法弄清楚错误在哪里。
答案 0 :(得分:0)
这是我对这个问题的处理方法:
public static void diamond3() {
System.out.println("Output for: Do while Loop");
int noOfRows =5;
int md=noOfRows%2;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
int i = noOfRows;
do {
//Printing i spaces at the beginning of each row
int j = 1;
do {
if (i-md==0) break;
System.out.print(" ");
j++;
}
while (j <= i-md);
//Printing j *'s at the end of each row
do {
if (i-md==0 && j==midRow+1){
System.out.print("o ");
} else {
System.out.print("* ");
}
j++;
}
while (j <= (noOfRows+1-md));
System.out.println();
i=(i - 2);
}
while (i >= 0);
i = 2;
do {
//Printing i spaces at the beginning of each row
int j = 1;
do {
System.out.print(" ");
j++;
}
while (j <= i);
do {
System.out.print("* ");
j++;
}
while (j <= (noOfRows+1-md));
System.out.println();
//Printing j *'s at the end of each row
i=(i + 2);
}
while (i <=noOfRows);
}