Loading

switch语句-方法重载等


返回 我的技术栈(Technology Stack)



switch语句注意事项


  • switch(表达式):

    • 基本数据类型可以接收byte,short,char,int
    • 引用数据类型可以接收枚举(JDK1.5)string
  • default一定要在最后吗?

  • 不是,可以在任意位置。但是建议在最后。

  • case后面只能是常量,不能是变量,而且,多个case后面的值不能出现相同的

测试


  int x = 1,y = 1;
  if(x++==2 & ++y==2)           
  {
	x =7;
  }
  System.out.println("x="+x+",y="+y);  //输出结果:x = 2,y = 2

  int x = 1,y = 1;
  if(x++==2 && ++y==2)      //&&左边判断为false后,不执行右边
  {
	x =7;
  }
  System.out.println("x="+x+",y="+y);  //输出结果:x = 2,y = 1

  int x = 1,y = 1;	
  if(x++==1 | ++y==1)
  {
	x =7;
  }
  System.out.println("x="+x+",y="+y);  //输出结果:x = 7, y = 2 

  int x = 1,y = 1;
  if(x++==1 || ++y==1)      //||左边判断为true后,不执行右边
  {
	x =7;
  }
  System.out.println("x="+x+",y="+y);   //输出结果:x = 7, y = 1

三个小知识点


int x = 10;  //这是两句话,int x 是声明语句,x = 10 是赋值语句

循环语句for(;;)      //外行
            for(;;)   //内列


return是结束方法
break是跳出循环
continue是终止本次循环继续下次循环

方法的练习例题


import java.util.Scanner;
class test1_method {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);     // 创建键盘录入对象
        System.out.println("请输入第一个整数:");
        int x = sc.nextInt();
        System.out.println("请输入第二个整数:");
        int y = sc.nextInt();

        int max = getMax(x , y);
        System.out.println(max);
}
    
    public static int getMax(int a,int b) {    //获取最大值的方法
        return a > b ? a : b;
}

}

方法重载


  • 概念:方法名相同,参数列表不同,与返回值类型无关

        public static int add(int a,int b){
       
        }
        pubilc static int add(int a,int b,int c) {
        
        }
    
  • 所调用的函数的类型是什么就用什么类型接收!

       public static void mian(string[],agrs){
            double a = add(10,20);
       }
       public static double add(int a ,int b){
            return a+b;
       }
    

posted @ 2021-03-27 23:08  言非  阅读(91)  评论(0编辑  收藏  举报