switch()适用byte、short、int、char
如果case 中不加break,会一直执行,知道},或break,结束
如:
执行结果是 d 、a、b
if与switch区别
if:
1.对具体的值进行判断
2.对区间进行判断
3.对运算结果是boolean类型的表达式进行判断
switch:
1.对具体的值进行判断
2.值的个数是固定的
PS:对于几个固定的值,最好使用switch,因为switch会一次性把具体的答案都加载进内存,效率相对较高
switch不大常用,功能性较差,且书写麻烦
在windows系统中回车符是 \r\n;
Linux系统是\n
函数:
函数的重载:
同函数名,参数类型不同,执行的功能特点一样,如:都是加,都是减,找最大
如果case 中不加break,会一直执行,知道},或break,结束
如:
- public class Main {
- public static void main(String[] args)
- {
- //int x = 5, y = 4,xx = 6;
- char a = 'f';
- switch(a)
- {
- default :System.out.println("d");
- case 'a':System.out.println("a");
- case 'b':System.out.println("b");break;
- case 'c':System.out.println("c");break;
- }
- // System.out.println("56");
- }
- }
执行结果是 d 、a、b
if与switch区别
if:
1.对具体的值进行判断
2.对区间进行判断
3.对运算结果是boolean类型的表达式进行判断
switch:
1.对具体的值进行判断
2.值的个数是固定的
PS:对于几个固定的值,最好使用switch,因为switch会一次性把具体的答案都加载进内存,效率相对较高
switch不大常用,功能性较差,且书写麻烦
在windows系统中回车符是 \r\n;
Linux系统是\n
函数:
函数的定义:
修饰符(public 可加可不加,起到一个权限的作用) 函数类型 函数名(参数类型 参数名,参数类型 参数名)
{
执行语句;
return 返回值;
}
- import java.util.Scanner;
- public class Main
- {
- public static void main(String[] args)
- {
- Scanner cin = new Scanner(System.in);
- int n = cin.nextInt();
- int a = cin.nextInt();
- int ans = sum(n,a);
- System.out.println("ans = " +ans);
- int ans1 = sub(a,n);
- System.out.println("ans1 = "+ans1);
- cin.close();
- }
- static int sum(int a,int b)//不加public
- {
- return a+ b;
- }
- public static int sub(int a,int b) //加public
- {
- return a-b;
- }
- }
函数的重载:
同函数名,参数类型不同,执行的功能特点一样,如:都是加,都是减,找最大
比较简单和特点C++基本相同
事例代码:
- import org.omg.CosNaming.NamingContextExtPackage.AddressHelper;
- public class Main
- {
- public static void main(String[] args)
- {
- int ans = add(4,5);
- int sum = add(5,6,7);
- System.out.println(ans);
- System.out.println(sum);
- }
- static int add(int x,int y)
- {
- return x +y;
- }
- static int add(int x,int y,int z)
- {
- // return x + y + z;
- return add(x, y) + z;/*前面已经定义过的额函数,就可以进行调用,
- 所以,函数重载,有一些重复的功能,可以互相调用*/
- }
- }