转载——大牛青春起点...

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. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章