JAVA學習日誌(循環)

循環

基礎語法循環


1.Switch (整型和字符)  

整數型(byte\char \ int \ short JDK 1.7以上可以使用字符串 


問題 爲什麼byteshort能在switch後面 但是long卻不能?

    

  因爲 byteshortint 小可以通過隱式轉換,而long如果轉換就是強制類型轉換



Swicth (整型數 {

  Case (常量     break;

  Case     常量     break

 ………..

Default

}


2. 三種循環 

For循環  

for (初始化計數;條件測試;再求值參數){

 語句 //如果是符合語句不能省略 

}

第一種

For (int i = 1; i <=100; i ++){

  System.out.println(i+”\t”);

}

  第二種 

     

      int i = 1;

for( ; i<=100;i++){

 system.out.println(i+”\t”);

}

 第三種 

 

   int i = 1;

for (; i<100; ){

 system.out.println(i+”\t”);

}

死循環

for ( ; ; ){

 system.out.println(“a”);

}


列題  輸出1100 ,並且每五個數字換一行

For (int I = 1 ; i<100; i++){

  If(i%5==0)

   System.out.println();

   Sytem.out.print(“\n”);

}



##break and Continue

 

注意:嵌套不能用過多,一般不能超過三層 

For( int I = 0; i<=100;i++){

   For (int j = 0 ; j <=100;j++){

 

}

 

}

  注:在寫system.out.print() 不能裏面是空的

 


Break 語句  // break是結束整個循環體  如果在多層循環中 break 向外跳出一層


  For (int I =1 ; i<5; i++){

     If(i==5)break;

   System.out.println(i);

}   答案是 1 2 3 4 


Continue語句 是結束單次循環 


Forint i= 0  i<8; i++{

  If(i== 5 )continue;

System.out.println(i);

}  結果是 0 1 2 3 4 6 7 8


##While循環 and  Do while循環 

while (表達式){

   語句 

}Do{

  語句

}while (表達式)


 while  for  do while 分別什麼時候使用?

如果循環次數固定 ,一般使用for循環


如果循環次數未知,一般使用while do while(至少可以允許一次)


發佈了43 篇原創文章 · 獲贊 1 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章