2011-02-13 11 views
25

decir que tengo las tres constantes siguientes:Encontrar el máximo de 3 números en Java con diferentes tipos de datos

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

quiero tomar la tres de ellos y utilizar Math.max() para encontrar el máximo de los tres pero si Paso más de dos valores, entonces me da un error. Por ejemplo:

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

Háganme saber lo que estoy haciendo mal.

Respuesta

64

Math.max solo toma dos argumentos. Si desea un máximo de tres, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).

+2

+1 yo estaba a punto de presentar la misma respuesta. –

+0

Debe haber una mejor manera cuando hay n valores involucrados. – mlissner

+2

@mlissner Sí, use un bucle y una variable 'max', compruebe cada variable, independientemente de si son mayores que 'max', de ser así: establezca 'max' en esa variable. Suponiendo que sus valores n están en una matriz, por supuesto. –

1

Como se mencionó antes, Math.max() sólo toma dos argumentos. No es exactamente compatible con su sintaxis actual, pero podría intentar Collections.max().

Si no te gusta que siempre puede crear su propio método para ello ...

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

Esto tomar cualquier número de argumentos numéricos mixtos (Integer, Double y flotar), pero el valor de retorno es un Objeto, por lo que tendrías que convertirlo en Integer, Double o Float.

También podría estar arrojando un error ya que no existe tal cosa como "MY_DOUBLE2".

+0

Ahora solo soy un novato, si alguien pudiera ayudarme a limpiar eso sería muy apreciado ... –

6

Sin el uso de bibliotecas de terceros, a llamar al mismo método más de una vez o la creación de una matriz, se puede encontrar el máximo de un número arbitrario de dobles al igual que

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

En su ejemplo, max podrían utilizarse como esto

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

Creo que la pregunta es acerca de usar 'Math.max' no recreando una función' max'. –

2

tengo una idea muy simple:

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

Por supuesto, si tiene 1000 numbers, es inutilizable, pero si tiene números 3 o 4, es fácil y rápido.

Saludos, Norbert

+0

Estoy bastante seguro de que la pregunta era sobre el número máximo ... no el número mínimo;) – Edd

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

si desea hacer una simple, será como esto

// 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 

y la salida será algo como esto

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

Referencias Java™ How To Program (Early Objects), Tenth Edition

+0

De alguna manera logró convertir un trazador de líneas en 40 líneas de código, incluida una definición de clase completamente innecesaria. Y lo llamó "simple" !? – Apollys

1

Java 8 vías.Que funciona para múltiples parámetros:

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

También podría usar 'DoubleStream' para comparar dobles. – jaco0646

2

puede utilizar esto:

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

o crear una función

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