2012-02-16 30 views
12

Me preguntaba si alguien podría ayudarme a encontrar el valor máximo de un conjunto de variables y asignarlas a otra variable. Aquí hay un fragmento de mi código que puede ayudar a entender de lo que estoy hablando.Cómo encontrar el valor máximo del conjunto de variables

// Ask for quarter values. 
    System.out.println("What is the value of the first quarter?"); 
    firstQuarter = input.nextDouble(); 

    System.out.println("What is the value of the second quarter?"); 
    secondQuarter = input.nextDouble(); 

    System.out.println("What is the value of the third quarter?"); 
    thirdQuarter = input.nextDouble(); 

    System.out.println("What is the value of the fourth quarter?"); 
    fourthQuarter = input.nextDouble(); 

    //Tell client the maximum value/price of the stock during the year.  
    //maxStock = This is where I need help 
    System.out.println("The maximum price of a stock share in the year is: $" + maxStock + "."); 

Respuesta

22

En Java, se puede utilizar Math.max así:

double maxStock = Math.max(firstQuarter, Math.max(secondQuarter, Math.max(thirdQuarter, fourthQuarter))); 

No es el más elegante, pero va a trabajar.

Alternativamente, para una solución más robusta definir la siguiente función:

private double findMax(double... vals) { 
    double max = Double.NEGATIVE_INFINITY; 

    for (double d : vals) { 
     if (d > max) max = d; 
    } 

    return max; 
} 

que luego se puede llamar por:

double maxStock = findMax(firstQuarter, secondQuarter, thirdQuarter, fourthQuarter); 
+0

Me disculpo pensé que esto estaba en el foro de Java o algo parecido. –

+0

@CodyBennett No se preocupe. He agregado la etiqueta Java para ti.Podría ayudar a obtener más respuestas si está buscando una respuesta diferente. – nybbler

+0

Esta solución está rota como está escrita. Double.MIN_VALUE devuelve "el menor valor positivo diferente de cero del tipo double", que es un número muy cercano a 0, NO el doble negativo más grande posible. En cambio, se podría usar algo como Double.NEGATIVE_INFINITY o -Double.MAX_VALUE. – ulmangt

0
Max = firstQuarter; 
If(secondQuarter > max) 
    Max = secondQuarter; 

... Y así sucesivamente

1
double [ ] data = { firstQuarter , secondQuarter , thirdQuarter , fourtQuarter) ; 
Arrays . sort (data) [ 3 ] ; 
2

Con variables primitivas la mejor opción quizá con matrices o Colecciones:

Arrays:

double [ ] data = { firstQuarter , secondQuarter , thirdQuarter , fourtQuarter) ; 
Arrays . sort (data) [ 3 ] ; 

Colecciones:

List<Double> data = new Arraylist<Double>(); 
data.add(firstQuarter); 
data.add(secondQuarter); 
data.add(thirdQuarter); 
data.add(foutQuarter); 
Collections.sort(data); 
data.get(3); 

Y si se trabaja con objetos que puede utilizar las colecciones con un Comparador:

class Quarter { 
    private double value; 
    private int order; 

    // gets and sets 
} 

Y para obtener el valor máximo:

List<Quarter> list = new ArrayList<Quarter>(); 
Quarter fisrt = new Quarter(); 
first.setValue(firstQuarter); 
first.setOrder(1); 
list.add(first); 
// Do the same with the other values 
Collections.sort(list, new Comparator<Quarter>(){ 
    compare(Object o1, Object o2){ 
     return Double.valueOf(o1.getValue()).compareTo(o2.getValue()); 
    } 
} 

Esto puede ser más complejo, pero si trabajas con objetos, creo que es mejor trabajar.

-3
import java.util.Scanner; 


public class dmar { 

public static void main (String [] srgs){ 

    Scanner dmar=new Scanner(System.in);{ 

     { 

System.out.println ("inter number of x plz") ; 

double x=dmar.nextDouble(); 

System.out.println ("inter number of y plz") ;{ 


double y=dmar.nextDouble(); 

System.out.println ("inter number of t plz") ; 
double t=dmar.nextDouble(); 

System.out.println ("inter number of f plz") ; 
double f=dmar.nextDouble(); 

{ 

{ 
if (x>y); 

System.out.println("x biger than y"); 


if (x>t); 
System.out.println("x biger than t"); 

if (x>f); 

System.out.println("x biger than f"); 


if (y>x); 
System.out.println("y biger than x"); 



if (y>t); 
System.out.println("y biger than t"); 

if (y>f); 
System.out.println("y biger than f"); 

if (t>x&t>f&t>y); 
System.out.println("t biger than x"); 

if (t>y); 
System.out.println("t biger than y"); 

if (t>f); 
System.out.println("t biger than f"); 

if (f>x); 
System.out.println("f biger than x"); 


if (f>y); 
System.out.println("f biger than y"); 


     if (f>t); 
System.out.println("f biger than t"); 

} 
4

Un método para gobernarlos a todos

public static <T extends Comparable<T>> T max(T...values) { 
    if (values.length <= 0) 
     throw new IllegalArgumentException(); 

    T m = values[0]; 
    for (int i = 1; i < values.length; ++i) { 
     if (values[i].compareTo(m) > 0) 
      m = values[i]; 
    } 

    return m; 
} 
1

Un poco tarde a la fiesta, pero para nadie más viendo esta pregunta, java 8 tiene tipos de trenes primitivos que implementan exactamente esto

Collection<Integer> values = new ArrayList<>(); 
OptionalInt max = values.stream().mapToInt((x) -> x).max(); 

es la función clave que describe cómo convertir la entrada a un tipo entero. La secuencia resultante tiene agregadores y recopiladores adicionales específicos para tipos enteros, uno de los cuales es max().

El valor resultante se puede extraer de la OptionalInt, si la operación se ha realizado correctamente

1

creo que ahora en Java 8 la versión más concisa se vería así:

DoubleStream.of(firstQuarter , secondQuarter , thirdQuarter , fourtQuarter).max(); 
Cuestiones relacionadas