当前位置:   article > 正文

Java之方法的重载(求最大值方法的重载)_求最大值方法对重载

求最大值方法对重载

重载:
在一个程序中可以定义多个名称相同的方法,但是参数类型和参数个数必须不同
Java中针对同一个类:
1.方法名相同
2.方法的参数不同(参数个数或类型)
3.方法的返回值类型不影响重载.
使用重载时,所输入的值必须和方法的参数一样!
如果两个方法名相同,参数也相同,但是返回值不同的话,不构成重载!

代码示例:

不仅可以求两个整数的最大值,还可以求两个小数的最大值,以及两个小数和一个整数的大小关系

public static void main(String[] args) {
        System.out.println("输入数字的个数为:");
        Scanner sc = new Scanner (System.in);
        int n = sc.nextInt();
        if(n==2){
            System.out.println("输入数字:");
            int a = sc.nextInt();
            int b = sc.nextInt();
            int num1 = max( a , b );
            System.out.println("最大值为:"+num1);//输出两个整数比较大小的值
            double c = sc.nextDouble();
            double d = sc.nextDouble();
            double num2 = max( c , d );
            System.out.println("最大值为:"+num2);//输出两个小数比较大小的值
        }else if (n==3){
            System.out.println("输入数字:");
            double e = sc.nextDouble();
            double f = sc.nextDouble();
            int g = sc.nextInt();
            double num3 = max( e , f , g );
            System.out.println("最大值为:"+num3);//输出两个小数和一个整数比较大小的值
        }
    }
    public static int max(int a,int b){
        return a>b?a:b;
    }
    public static double max(double a,double b){
        return a>b?a:b;
    }
    public static double max(double a,double b,int c){
        return max(a,b)>c?max(a,b):c;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/468120
推荐阅读
相关标签
  

闽ICP备14008679号