現在有一個需求:打印1-100的數字,每10個換一行。
如果我們直接使用輸出語句的話,會打印到崩潰。。。
Java中除了有順序結構、選擇結構,也有循環結構,可以用循環結構來解決這個問題:從定義一個變量一開始為1,每輸出一個數,變量就+1,直到變量等於100,就結束。
Java中有三種循環:while,do...while,for
1.while
語法:
初始化語句;
while(條件表達式)
{ //循環體
//滿足條件(為 true 時)執行語句
//迭代語句(退出機制,當不再滿足條件時就會退出)
}
//不滿足條件則會直接跳過
package com.dh.control;
public class WhileDemo {
public static void main(String[] args) {
//1.初始化變量
int i = 1;
//count用於計數(10個數換一行)
int count = 0;
while(i<=100){ //2.條件表達式
//3.執行語句
System.out.print(i+"\t");
count++; //計數器+1
if(count%10 == 0){
System.out.println();
}
//4.迭代語句(退出機制)
i++;
}
}
}

注意:如果沒有退出機制,或者條件永遠為true時,程序就沒有辦法跳出循環,程序就會一直運行,稱為死循環。
一定要盡量避免書寫死循環程序,除非真的有使用死循環的需求!
while(true){
}
2.do...while
語法:
初始化語句;
do{
//循環執行體
//迭代語句
}while(條件表達式); //不滿足條件表達式則跳過則結束循環語句
將上述問題,采用do...while循環來解決:
package com.dh.control;
public class DoWhile {
public static void main(String[] args) {
int i = 1;
int count = 0;
do{
System.out.print(i+"\t");
i++;
count++;
if(count%10 == 0){
System.out.println();
}
}while (i<=100);
}
}

那while和do...while有什么區別呢?看下面這個案例
package com.dh.control;
public class Demo {
public static void main(String[] args) {
int i = 1;
//do...while
do {
System.out.println("do...while執行了");
} while (i < 0);
//while
while (i < 0) {
System.out.println("while執行了");
}
}
}

通過觀察實驗結果,可以看出do...while和while的用法是一致的,只不過do…while 先執行再判斷(無論如何都會先執行一次循環執行體中的代碼)、while 是先判斷再執行,如果條件一開始就不滿足,就不會執行循環執行體代碼。
3.for
語法:
for((1)初始化變量;(2)條件;(4)更新循環遍歷){
//(3)循環體
}
(按照 1234 的順序執行,1 和 4 可以放在外部,2 省略了的話沒有結束條件將會死循環)
我們再用for來解決上述問題:
package com.dh.control;
public class ForDemo {
public static void main(String[] args) {
int count = 0;//計數器
for(int i = 1;i<=100;i++){ //初始化變量;結束條件;迭代變量(退出機制)
System.out.print(i+"\t");
count++;
if(count%10 == 0){
System.out.println();
}
}
}
}

可以看到,也是可以輸出結果的,在大多數情況下,for循環會比while、do...while循環更簡潔,推薦使用for循環!
將初始化變量和變量迭代放在for()外,也是可以的,但是建議放在里面:

4.break和continue的用法和區別
break
如果現在改了需求呢:我想決定我什么時候不再輸出了,即我想讓它輸出到多少就到多少。
此時就需要一個還未等到循環終止條件,就強制退出的機制,在switch的時候,我們使用了break,在while里也是一樣的。
此處使用for循環作為循環結構:while和do...while同理
package com.dh.control;
public class BreakDemo {
public static void main(String[] args) {
int count = 0;
for(int i = 1;i<=100;i++){
System.out.print(i+"\t");
//使用break退出循環
if(i == 55){
break;
}
count++;
if(count%10 == 0){
System.out.println();
}
}
}
}

可以看到,程序輸出到55的時候就不再繼續輸出了。
continue
但是此時我們又修改了需求呢,我想打印1-100之間除了5的倍數的數,一行輸出8個。
此時通過分析需求,只要我們可以跳過某次循環,即5的倍數的時候就跳過,再繼續循環,就可以達到目的了。
Java使用continue來跳出當前次的循環
package com.dh.control;
public class ContinueDemo {
public static void main(String[] args) {
int count = 0; //計數器
for(int i = 1;i<=100;i++){ //初始化變量;結束條件;迭代變量(退出機制)
//使用continue跳出當前循環,遇到continue就跳出,不再執行剩余循環執行體里面的代碼
//回到for
if(i % 5 == 0){
continue;
}
System.out.print(i+"\t");
count++;
if(count%8 == 0){
System.out.println();
}
}
}
}
我們來看看結果:

結果是達到了我們的需求的。
總結:
-
break:用於跳出整個循環。(通常在循環中與條件語句一起使用,也可用於選擇語句);
-
continue:跳過當前次循環,即跳過循環體中剩余的語句而執行下一次循環(只能用在循環里,也通常和條件語句一起使用,加速循環)。
有錯誤望指出~
