繁体   English   中英

用不同的数据类型在 Java 中找到最多 3 个数字

[英]Find the max of 3 numbers in Java with different data types

假设我有以下三个常量:

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

我想取其中三个并使用Math.max()来找到三个的最大值,但是如果我传入两个以上的值,那么它会给我一个错误。 例如:

// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);

请让我知道我做错了什么。

Math.max只接受两个参数。 如果您想要最多三个,请使用Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2))

如果可能,请在 Apache Commons Lang 中使用 NumberUtils - 那里有很多很棒的实用程序。

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])

NumberUtils.max(int[])

你可以使用这个:

 Collections.max(Arrays.asList(1,2,3,4));

或者创建一个函数

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

Math.max只接受两个参数,不多也不少。

已经发布的答案的另一种不同解决方案是使用DoubleStream.of

double max = DoubleStream.of(firstValue, secondValue, thirdValue)
                         .max()
                         .getAsDouble();

不使用第三方库,多次调用相同的方法或创建数组,您可以像这样找到任意数量的双打的最大值

public static double max(double... n) {
    int i = 0;
    double max = n[i];

    while (++i < n.length)
        if (n[i] > max)
            max = n[i];

    return max;
}

在您的示例中,可以像这样使用max

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;

public static void main(String[] args) {
    double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}

Java 8 方式。 适用于多个参数:

Stream.of(first, second, third).max(Integer::compareTo).get()

我有一个非常简单的想法:

 int smallest = Math.min(a, Math.min(b, Math.min(c, d)));

当然,如果您有1000 numbers ,则无法使用,但是如果您有34号码,则既简单又快捷。

问候, 诺伯特

如前所述,Math.max() 只接受两个参数。 它与您当前的语法并不完全兼容,但您可以尝试 Collections.max()。

如果您不喜欢那样,您可以随时为它创建自己的方法......

public class test {
    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;

    public static void main(String args[]) {
        double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
    }

    public static Object multiMax(Object... values) {
        Object returnValue = null;
        for (Object value : values)
            returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
                    : (value instanceof Double) ? (Double) value
                            : (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
                    : (returnValue instanceof Double) ? (Double) returnValue
                            : (Float) returnValue)) ? value : returnValue)
                    : value;
        return returnValue;
    }
}

这将采用任意数量的混合数字参数(整数、双精度和浮点数),但返回值是一个对象,因此您必须将其转换为整数、双精度或浮点数。

它也可能抛出错误,因为没有“MY_DOUBLE2”这样的东西。

int first = 3;  
int mid = 4; 
int last = 6;

//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which  //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));

你可以这样做:

public static void main(String[] args) {

    int x=2 , y=7, z=14;
    int max1= Math.max(x,y);

    System.out.println("Max value is: "+ Math.max(max1, z)); 
}  

如果你想做一个简单的,它会是这样的

// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;

public class MaximumFinder
{
  // obtain three floating-point values and locate the maximum value
  public static void main(String[] args)
  {
    // create Scanner for input from command window
    Scanner input = new Scanner(System.in);

    // prompt for and input three floating-point values
    System.out.print(
      "Enter three floating-point values separated by spaces: ");
    double number1 = input.nextDouble(); // read first double
    double number2 = input.nextDouble(); // read second double
    double number3 = input.nextDouble(); // read third double

    // determine the maximum value
    double result = maximum(number1, number2, number3);

    // display maximum value
    System.out.println("Maximum is: " + result);
  }

  // returns the maximum of its three double parameters          
  public static double maximum(double x, double y, double z)     
  {                                                              
    double maximumValue = x; // assume x is the largest to start

    // determine whether y is greater than maximumValue         
    if (y > maximumValue)                                       
      maximumValue = y;                                        

    // determine whether z is greater than maximumValue         
    if (z > maximumValue)                                       
      maximumValue = z;                                        

    return maximumValue;                                        
  }                                                              
} // end class MaximumFinder

输出将是这样的

Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35

参考资料Java™ How To Program (Early Objects),第十版

没有方法的简单方法

int x = 1, y = 2, z = 3;

int biggest = x;
if (y > biggest) {
    biggest = y;
}
if (z > biggest) {
    biggest = z;
}
System.out.println(biggest);
//    System.out.println(Math.max(Math.max(x,y),z));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM