有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建获取4个数字并返回最大数字的max方法?

我正在尝试构建一个方法,该方法将获得4个数字,并返回其中的最大数字

我试图编写这段代码,得到4个数字,但这不起作用:

输入和输出:

double a = Math.max(10, 5, 4, 3);
    System.out.println(a);

public static int max(int a, int b, int c, int d) {
    if (a > b && a > c && a > d)
        return a;
    if (b > a && b > c && b > d)
        return b;
    if (c > a && c > b && c > d)
        return c;
    if (d > b && d > c && d > a)
        return d;
}

共 (6) 个答案

  1. # 1 楼答案

    if (c > a && c > b && c > d)
        return d;
    

    这里你返回的是d而不是c

  2. # 2 楼答案

    我将通过引入变量max来简化这个过程:

    public static int max(int a, int b, int c, int d) {
    
        int max = a;
    
        if (b > max)
            max = b;
        if (c > max)
            max = c;
        if (d > max)
            max = d;
    
         return max;
    }
    

    你也可以用^{},如suggestedby fast snail,但因为这似乎是家庭作业,我更喜欢算法解决方案

    Math.max(Math.max(a,b),Math.max(c,d))
    
  3. # 3 楼答案

    尝试Math.max如下所示:

    return Math.max(Math.max(a, b), Math.max(c, d));
    
  4. # 4 楼答案

    您始终可以使用这样的方法,该方法可以对任意数量的整数进行处理:

    public static Integer max(Integer... vals) {
        return new TreeSet<>(Arrays.asList(vals)).last();
    }
    

    例如,呼叫:

    System.out.println(max(10, 5, 17, 4, 3));
    
  5. # 5 楼答案

    还有一种方法

    public static int max(int a, int b, int c, int d) {
        if (a > b && a > c && a > d)
            return a;
        if (b > c && b > d)
            return b;
        if (c > d)
            return c;
        return d;
    }
    
  6. # 6 楼答案

    public static int max(Integer... vals) {
        return Collections.max(Arrays.asList(vals));
    }