舉例講授Java中do-while語句的應用辦法。本站提示廣大學習愛好者:(舉例講授Java中do-while語句的應用辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是舉例講授Java中do-while語句的應用辦法正文
在進修 do/while 語句之前,先清晰 while 語句是若何任務的。while 語句是先輩行前提斷定,再履行年夜括號內的輪回體。
do/while 語句與 while 語句分歧的是,它先履行年夜括號內的輪回體,再斷定前提,假如前提不知足,下次不在履行輪回體。也就是說,在斷定前提之前,就曾經履行年夜括號內的輪回體。
示例:盤算1+2+3+4......+100的成果。
public class control5{
public static void main(String[] args){
int a=1,result=0;
do{
result+=a++;
}while(a<=100);
System.out.println(result);
}
}
do-while聲明時,至多一次會輪回一次,。
它的語法以下:
do {
statement (s)
} while (booleanexpression);
簡略實例
public class mainclass {
public static void main(string[] args) {
int i = 0;
do {
system.out.println(i);
i++;
} while (i < 3);
}
}
以下do-while注解至多做塊的代碼會被履行,即便一次的初始值,用於測試的表達[j]. . < 3盤算毛病的。
public class mainclass {
public static void main(string[] args) {
int j = 4;
do {
system.out.println(j);
j++;
} while (j < 3);
}
}
應用do while來乞降
public class mainclass {
public static void main(string[] args) {
int limit = 20;
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= limit);
system.out.println("sum = " + sum);
}
}
總結一下三種輪回的差別:
1.while輪回先斷定->決議能否履行輪回
2.do-while是先履行輪回->斷定能否->再持續看能否
3.for輪回:先履行初始化輪回;然後履行斷定,先挪用,後履行輪回體的內容,將變量值打印出來;然後再才履行參數修正的部門。就是先斷定再履行。