轉載——大牛青春起點...

switch()適用byte、short、int、char,string

如果case 中不加break,會一直執行,知道},或break,結束

如:


[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. public class Main {  
  2.   
  3.   
  4.     public static void main(String[] args)  
  5.     {  
  6.         //int x = 5y = 4,xx = 6;  
  7.         char a = 'f';  
  8.         switch(a)  
  9.         {  
  10.         default :System.out.println("d");  
  11.         case 'a':System.out.println("a");  
  12.         case 'b':System.out.println("b");break;  
  13.         case 'c':System.out.println("c");break;  
  14.           
  15.         }  
  16.           
  17.           
  18.     //  System.out.println("56");  
  19.     }  
  20. }  


執行結果是 d 、a、b


if與switch區別
if:
1.對具體的值進行判斷
2.對區間進行判斷
3.對運算結果是boolean類型的表達式進行判斷


switch:
1.對具體的值進行判斷
2.值的個數是固定的
PS:對於幾個固定的值,最好使用switch,因爲switch會一次性把具體的答案都加載進內存,效率相對較高
switch不大常用,功能性較差,且書寫麻煩


在windows系統中回車符是 \r\n;
Linux系統是\n


函數:



函數的定義:


修飾符(public 可加可不加,起到一個權限的作用) 函數類型 函數名(參數類型 參數名,參數類型 參數名)

執行語句;
return 返回值;


[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import java.util.Scanner;  
  2.   
  3.   
  4. public class Main  
  5. {  
  6.     public static void main(String[] args)  
  7.     {  
  8.         Scanner cin = new Scanner(System.in);  
  9.         int n = cin.nextInt();  
  10.         int a = cin.nextInt();  
  11.         int ans = sum(n,a);  
  12.         System.out.println("ans = " +ans);  
  13.         int ans1 = sub(a,n);  
  14.         System.out.println("ans1 = "+ans1);  
  15.         cin.close();  
  16.     }  
  17.     static int sum(int a,int b)//不加public  
  18.     {  
  19.         return a+ b;  
  20.     }  
  21.     public static int sub(int a,int b) //加public  
  22.     {  
  23.         return a-b;  
  24.     }  
  25.       
  26. }  





函數的重載:

同函數名,參數類型不同,執行的功能特點一樣,如:都是加,都是減,找最大

比較簡單和特點C++基本相同


事例代碼:

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. import org.omg.CosNaming.NamingContextExtPackage.AddressHelper;  
  2.   
  3.   
  4. public class Main   
  5. {  
  6.     public static void main(String[] args)  
  7.     {  
  8.         int ans = add(4,5);  
  9.         int sum = add(5,6,7);  
  10.         System.out.println(ans);  
  11.         System.out.println(sum);  
  12.     }  
  13.     static int add(int x,int y)  
  14.     {  
  15.         return x +y;  
  16.     }  
  17.     static int add(int x,int y,int z)  
  18.     {  
  19.     //  return x + y + z;  
  20.         return add(x, y) + z;/*前面已經定義過的額函數,就可以進行調用,  
  21.                               所以,函數重載,有一些重複的功能,可以互相調用*/  
  22.     }  
  23.       
  24. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章