我试图将while循环中的代码转换为For循环,但是Im没有得到所需的输出。将while循环中的整个代码转换为Java中的For循环
For循环代码:
public static void diamond1() {
System.out.println("Diamond Height: " + DIAMOND_SIZE);
System.out.println("Output for: For Loop");
int noOfRows = DIAMOND_SIZE;
int md=noOfRows%2;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
//Printing upper half of the diamond
for (int i = noOfRows; i >= 0;i=(i-2))
{
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i-md; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
for (int j = 1; j <= (noOfRows+1-md); j++) {
if (i-md==0 && j==midRow+1) {
System.out.print("o ");
}
else {
System.out.print("* ");
}
}
System.out.println();
}
//Printing lower half of the diamond
for (int i = 2; i <= noOfRows;i=(i+2)) {
//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=0; j <= (noOfRows); j++) {
System.out.print("* ");
}
System.out.println();
}
}
,我得到的输出是:
* * *
* o *
* * * *
需要的输出是:
*
* o *
*
原来while循环我有是:
public static void diamond2() {
System.out.println("");
System.out.println("Output for: While loop");
int noOfRows = DIAMOND_SIZE;
int md=noOfRows%2;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
int i = noOfRows;
while(i >= 0){
//Printing i spaces at the beginning of each row
int j = 1;
while(j <= i-md){
if(i-md==0)break;
System.out.print(" ");
j++;
}
//Printing j *'s at the end of each row
while(j <= (noOfRows+1-md)){
if (i-md==0 && j==midRow+1) {
System.out.print("o ");
}
else {
System.out.print("* ");
}
j++;
}
System.out.println();
i=(i-2);
}
i = 2;
while(i <= noOfRows){
//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
while(j <= (noOfRows+1-md)){
System.out.print("* ");
j++;
}
System.out.println();
i=(i+2);
}
}
有人可以帮我弄清楚我在这里做错了吗?
你的调试器将帮助你在这里。 –
@AndyTurner我知道这可能听起来很愚蠢,但我该如何调试呢? – donk2017
你最初的while循环是什么? –