Java從入門到精通之流程控制語句章節筆記

流程控制語句章節需要注意的:

  • foreach語句
public class Foreach {
   public static void main(String[] args) {
	   int arr[] = {7,8,9,10};
	   for(int x:arr) {
		   System.out.println(x);
	   }
   }
}

foreach語句用於遍歷對象,語法如上。任何foreach語句都可以改寫成for語句,反之不成立。

  • break語句支持跳出外層循環
public class Breaktab {
   public static void main(String[] args) {
	   loop: for(int i=0;i<8;i++) {
		   for(int j=0;j<3;j++) {
			   if(i*j>10) {
	               System.out.println(i*j);
				   break loop;
			   }
		   }
	   }
   }
}

  • 練習1 (打印菱形)
public class Printdiamond {
    public static void main(String[] args) {
    	for(int i=0;i<5;i++) {
    		for(int j = 0;j<4;j++) {
    			System.out.print("*");
    		}
    		System.out.println("\n");
    	}
    }
}


  • 練習2 (使用while語句計算1+1/2!+1/3!+1/4!..1/20!的和)
public class ComputedSum {
   public static void main(String[] args) {
	   int i = 1;
	   double sum=0;
	   while(i<=20) {
		   int j = 1;
		   double subsum=1;
		   while(j<=i) {
			   subsum*=j;
			   j++;
		   }
		   sum+= 1/subsum;
		   i++;
	   }
	   System.out.println(sum);
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章