[英]Incorrect output when printing diamond using do while loop
I am creating code to print a diamond using only Do while loops and I have got the following code:我正在创建代码以仅使用 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);
}
Im meant to get a diamond shape but I am getting the following shape:我想得到一个菱形,但我得到了以下形状:
*
* *
* o *
* *
*
The expected out is:预期输出是:
*
* * *
* * o * *
* * *
*
Can someone help figure out where I have gone wrong.有人可以帮助找出我哪里出错了。 I have checked the code so many times but unable to figure out where the mistake is.
我已经检查了很多次代码,但无法弄清楚错误在哪里。
This is my approach to this question:这是我对这个问题的处理方法:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.