[英]Printing a Diamond with * and “o” in the centre using do while loop in java
Im trying to print a Diamond with * and "o" in the centre using do while loop. 我正在尝试使用do while循环在中心打印带有*和“ o”的Diamond。 I have already done this with For loop but unsure how to change it to while loop.
我已经使用For循环完成了此操作,但是不确定如何将其更改为while循环。 Can anyone give some support.
任何人都可以提供一些支持。
public static void diamond1() {
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--;
}
}
How would I go about doing this? 我将如何去做呢?
In general, a for loop like this: 通常,这样的for循环:
for (command1; statement; command2){
// Code to loop
}
is equal to this while loop: 等于以下while循环:
command1;
while(statement){
// Code to loop
command2;
}
and equal to this do-while loop: 并等于此do-while循环:
command1;
do{
if (statement){
// Code to loop
command2;
}
} while(true);
If it is certain that the first loop must happen then you can use the below do-while: 如果确定必须发生第一个循环,则可以使用以下do-while:
command1;
do{
// Code to loop
command2;
} while(statement);
Here you go : 干得好 :
public static void Diamond() {
int DIAMOND_SIZE = 5;
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;
int i = midRow;
while(i > 0){
//Printing i spaces at the beginning of each row
int j = 1;
while(j <= i){
System.out.print(" ");
j++;
}
//Printing j *'s at the end of each row
j = 1;
while(j <= row){
System.out.print("* ");
j++;
}
System.out.println();
//Incrementing the row
row++;
i--;
}
i = 0;
while(i <= midRow){
//Printing i spaces at the beginning of each row
int j = 1;
while(j <= i){
System.out.print(" ");
j++;
}
//Printing j *'s at the end of each row
int mid = (row+1) / 2;
j = row;
while(j > 0){
if(i == 0 && j == mid)
System.out.print("o ");
else
System.out.print("* ");
j--;
}
System.out.println();
//Decrementing the row
row--;
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.