English 中文(简体)
在Java中查找具有不同数据类型的最多3个数字
原标题:Find the max of 3 numbers in Java with different data types
  • 时间:2011-02-13 03:14:37
  •  标签:
  • java
  • math
  • max

假设我有以下三个常数:

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:

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

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

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

在不使用第三方库、多次调用同一方法或创建数组的情况下,您可以找到任意数量的双精度的最大值,如下所示

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);
}

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

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

当然,如果你有<code>1000个</code>的数字,它是不可用的,但如果你有>code>3个</code>或<code>4个<-code>的数字,那就简单快捷了。

Regards, Norbert

如前所述,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;
    }
}

这将采用任意数量的混合数字参数(Integer、Double和Float),但返回值是Object,因此必须将其强制转换为Integer、Double或Float。

它也可能抛出一个错误,因为没有“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语言™ 如何编程(早期对象),第十版

没有方法的简单方法

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));




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...