1. 程式人生 > 遊戲 >《超級機器人大戰30》於12月10日進行直播 屆時公開最新情報

《超級機器人大戰30》於12月10日進行直播 屆時公開最新情報

while迴圈

while(布林表示式){
//迴圈內容
}
  • 只要布林表示式為true,迴圈就會一直執行下去

  • 多少情況要讓迴圈停下,需要一個讓表示式失效的方式來結束迴圈

  • 少數情況需要迴圈一直執行,如伺服器的請求響應監聽

  • 迴圈條件一直為true會造成死迴圈,正常程式設計業務應儘量避免死迴圈,會影響效能或者造成卡死崩潰

  • 輸出1~100:

package struct;

/**
* @author IT_Jay
* @date 2021/12/12 18:36
*/

public class Demo08 {
public static void main(String[] args) {
//輸出1~100
int i = 0;
while (i<100){
i++;
System.out.println(i); //輸出1~100
}
System.out.println(i); //輸出100
}
}

  • 輸出1+2+3+4+…..+100:

package struct;

/**
* @author IT_Jay
* @date 2021/12/12 18:40
*/

public class Demo09 {
public static void main(String[] args) {
//1+2+3+。。。。+100=?
int i = 0;
int sum = 0;
while (i<=100){
sum = sum + i;
i++;
}
System.out.println(sum);
}
}

  • 錯誤寫法:

while(i<=100){
i++;
sum += i; //當i=99時,進入迴圈即為1~100之和;i=100時,i++值為101,sum為1~101之和
}

do…while迴圈

  • while迴圈中,不滿足條件不能進入迴圈,先判斷後執行

  • do while迴圈至少會執行一次,先執行後判斷

package struct;

/**
* @author IT_Jay
* @date 2021/12/12 19:15
*/

public class Demo10 {
public static void main(String[] args) {
int i= 0;
int sum = 0;
do {
sum +=i;
i++;
}while (i<=100);
System.out.println(sum);
}
}

package struct;

/**
* @author IT_Jay
* @date 2021/12/12 19:22
*/

public class Demo11 {
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=0
a++;
}while (a<0); //不滿足,跳出
System.out.println(a); //do語句中進行了一次自加,a=1
}
}