2012-02-16 13 views
12

Mi chiedevo se qualcuno potesse aiutarmi a trovare il valore massimo di un insieme di variabili e assegnarle a un'altra variabile. Ecco uno snippet del mio codice che può aiutare a capire di cosa sto parlando.Come trovare il valore massimo del set di variabili

// 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 + "."); 

risposta

22

In Java, è possibile utilizzare Math.max come questo:

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

Non il più elegante, ma funzionerà.

In alternativa, per una soluzione più robusta definire la seguente funzione:

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

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

    return max; 
} 

che è quindi possibile chiamare da:

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

mi scuso ho pensato che questo era sotto il forum Java o qualcosa del genere. –

+0

@CodyBennett Nessun problema. Ho aggiunto il tag Java per te.Potrebbe essere utile ottenere più risposte se stai cercando una risposta diversa. – nybbler

+0

Questa soluzione è interrotta come scritto. Double.MIN_VALUE restituisce "il più piccolo valore positivo diverso da zero del tipo double", che è un numero molto vicino a 0, NON il più grande doppio negativo possibile. Invece, potrebbe essere usato qualcosa come Double.NEGATIVE_INFINITY o -Double.MAX_VALUE. – ulmangt

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

... E così via

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

Con variabili primitive la scelta migliore magari con array o Collezioni:

Matrici:

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

Collezioni:

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

E se si lavora con gli oggetti si possono utilizzare collezioni con un comparatore:

class Quarter { 
    private double value; 
    private int order; 

    // gets and sets 
} 

E per ottenere il valore massimo:

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

Questo può essere più complesso, ma se lavori con gli oggetti penso che sia meglio lavorare.

-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 metodo per domarli tutti

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 po 'tardi alla festa, ma per chiunque altro la visualizzazione di questa domanda, Java 8 ha i tipi di flusso primitivi che implementano esattamente questo

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

mapToInt è la funzione chiave che descrive come convertire l'input in un tipo intero. Il flusso risultante quindi ha aggregatori e collettori aggiuntivi specifici per i tipi interi, uno dei quali è max().

Il valore del risultato può quindi essere estratto dal OptionalInt, se l'operazione ha avuto successo

1

credo ora in Java 8 la versione più concisa sarebbe simile a questa:

DoubleStream.of(firstQuarter , secondQuarter , thirdQuarter , fourtQuarter).max(); 
Problemi correlati