/**
* while(A表達式)
* {
* B語句塊;
* }
*
* 執行步驟:
* 1.判斷A表達式
* 返回true,執行B語句塊,繼續進行步驟1的判斷
* 返回false,結束循環
* =========================================================
* do{
* B語句塊
* }while(A表達式);
*
* 執行步驟:
* 1.執行B語句塊
* 2.判斷A表達式
* 返回true,執行B語句塊,繼續進行步驟2的判斷
* 返回false,結束循環
*
*
* while: 先判斷,再執行
* do..while: 先執行一次,再判斷
*
*/
//while 循環輸出1~10之間的整數
int i = 1;
while( i<=10 )
{
//System.out.println(i);
i++;
}
//do..while..循環輸出1~10之間的整數
int k = 1;
do
{
System.out.println(k);
k++;
}while(k<=10);//分號必須有
//死循環
/*while(true)
{
System.out.println("死循環");
}*/
/*int j =1;
while( j<=10 )
{
System.out.println(j);
//j++; //忘記自增條件
}*/
Scanner scanner = new Scanner(System.in);
//死循環
while(true)
{
System.out.println("死循環說:");
String content = scanner.nextLine();
if(!"exit".equals(content))
{
System.out.println(content);
}
else
{
break;//創造條件終止循環
}
}
/**
*
* for(初始化表達式;循環條件表達式;循環後的操作表達式)
* {
* 語句塊;
* }
*
* 執行步驟:
* A初始化表達式(僅執行一次)
* B循環條件表達式
C語句塊 1
---------------------------
D循環後的操作表達式
B循環條件表達式
C語句塊 2
---------------------------
D循環後的操作表達式
B循環條件表達式
C語句塊 3
---------------------------
D循環後的操作表達式
B循環條件表達式,不滿足條件,終止循環
*
*/
public static void main(String[] args) {
//輸出1~10之間的整數
for(int i=1;i<=10;i++)
{
//System.out.println(i);
}
//測試for執行步驟
int i = 1;
for (System.out.println("A初始化表達式"); i <= 3; System.out.println("D循環後的操作表達式")) {
System.out.println("C語句塊 " + i);
i++;
System.out.println("---------------------------");
}
/**
* 終止循環語句:
* break語句:終止整個循環
* continue語句:終止當前循環
* break label:終止指定的名稱爲lable的循環
*/
public static void main(String[] args) {
//break語句
/*int i=1;
while(i<=10)
{
if(i%3==0)
{
break; //跳出循環,終止整個循環
}
System.out.println(i);
i++;
}*///1 2
//continue語句
/*int j=0;
while(j<=10)
{
if(j%3==0)
{
j++;
continue;//3 6 9終止本次循環,進入下一次循環
}
System.out.println(j);
j++;
}*///1 2 4 5 7 8 10
//break label語句
//外部循環
outer:for (int i = 1; i <= 10; i++) {
System.out.println("outer:"+i);
//內部循環
inner:while(true)
{
Scanner scanner = new Scanner(System.in);
String content = scanner.nextLine();
System.out.println("inner:" + content);
if("exit inner".equals(content))
{
break inner;//終止內部循環
}
else if("exit outer".equals(content))
{
break outer;//終止外部循環
}
}
}