循环结构, while, do……while
生活随笔
收集整理的這篇文章主要介紹了
循环结构, while, do……while
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
循環結構
- while循環
- do……while循環
- for 循環
- 在Java5引入一種主要用于數組增強型for循環
while循環
- while是最基本的循環,結構為:
- 只要布爾表達式為true,就會一直循環下去
- 我們大多數情況會有循環停下來,需要一個表達式失效的方式來結束循環
- 少部分需要循環一直執行,比如服務器的請求響應監聽等
- 循環條件一直我true就會變成死循環,在正常業務編程要避免死循環。會影響程序性能或造成程序卡死崩潰
- 思考:計算1+2+3+……+100=?
- 輸出1-100
do……while循環
- 對于while語句,如果不滿足條件,就不能進入循環。但是有的時候我們需要即使不滿足條件也至少執行一次。
- do……while循環和while循環相似,不同的是,do……while循環至少執行一次
- 語法
-
while和do……while的區別:
-
while先判斷后執行,do……while先執行再判斷!
-
do……while總是保證循環體至少會執行一次!這是他們的主要區別。
package com.boss.struct;public class DowhileDemo02 {public static void main(String[] args) {int a=0;while (a<0){System.out.println(a);a++;}System.out.println("_____________________________________");do {System.out.println(a);a++;}while (a<0);} } D:\開發工具\java\bin\java.exe "-javaagent:D:\開發工具\IDEAIU\IntelliJ IDEA 2020.1\lib\idea_rt.jar=1093:D:\開發工具\IDEAIU\IntelliJ IDEA 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\java學習\代碼\out\production\代碼 com.boss.struct.DowhileDemo02 _____________________________________ 0進程已結束,退出代碼 0
代碼
package com.boss.struct;public class DowhileDemo01 {public static void main(String[] args) {//計算1+2+3+……+100=?int i=0;int t=0;do{t=t+i;i++;}while (i<=100);System.out.println(t);} }for循環
總結
以上是生活随笔為你收集整理的循环结构, while, do……while的全部內容,希望文章能夠幫你解決所遇到的問題。