[英]Change for-loop to a while
如何將以下代碼更改為 while-loop?
for (int i = 12; i < 40; i += 14) {
for (int j = 30; j > 10; j -= 9) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
}
}
我試過這個,但它不工作:
public class WhileExample {
public static void main(String[] args) {
int i = 12;
int j = 10;
while (i <= 40) {
while (j <= 30) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
j++;
}
i++;
}
}
}
您正在尋找的答案:
int i = 12;
while (i < 40) {
int j = 30;
while (j > 10) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
j -= 9;
}
i += 14;
}
你這里有幾個問題。 首先,您需要在for
和while
循環中保留相同的條件。 其次,您需要使用與for
循環相同的增量,而不僅僅是++
調用。 第三,你沒有像在循環中那樣初始化j
,初始化應該在外循環內完成:
public class WhileExample {
public static void main(String[] args) {
int i = 12;
while (i < 40) {
int j = 30;
while (j > 10) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
j -= 9;
}
i += 14;
}
}
}
以下是您的問題的工作代碼,您不會再次將j
的值設為默認值,
public class WhileExample {
public static void main(String[] args) {
int i = 12;
int j = 30;
while (i < 40) {
while (j > 10) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
j -= 9;
}
i += 14;
j = 30;
}
}
}
要將任何for
循環轉換為while
循環,您必須了解兩個循環的結構。 一般來說,兩個循環的構造如下:
for循環
for (loop counter initialization; break condition; counter increment/decrement) {
body of loop
}
while循環
while (break condition) {
body of loop
}
while
循環中唯一缺少的是計數器初始化和計數器遞減/遞增。 通常,當您需要循環計數器時,您將使用for
循環。 當您不需要循環計數器時,您將使用while
循環。 但是,這不是語言強制執行的規則。 您可以執行以下操作來使用帶有計數器變量的while
循環:
int counter = 0;
while (break condition) {
body of loop
counter++;
}
或者,如果您想使用不帶計數器的for
循環:
for (;break condition;) {
body of loop
}
甚至像這樣更瘋狂的東西:
for (;;) {
body of loop
if (break condition) {
break;
}
}
顯然,最好的辦法是將循環用於其預期目的:需要循環計數器時使用 for 循環,不需要時使用 while 循環。
根據此處的信息,您應該能夠看到:
for (int i = 12; i < 40; i += 14) {
for (int j = 30; j > 10; j -= 9) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
}
}
應翻譯為:
int i = 12;
while (i < 40) {
int j = 30; // initializing this outside the outer `while` is a logic error
while (j > 10) {
System.out.println(i + "+" + j + "=" + (i + j) + "");
j -= 9;
}
i += 14;
}
實現這種轉換的最簡單方法是從內到外開始。 意思是,go 到最里面的循環,按照我的建議進行轉換,然后解決問題。 無論您的循環有多嵌套,您都應該能夠將任何for
轉換為while
循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.