2017-04-07 4 views
0

Derzeit gibt mein Code den höchsten Temperaturwert zurück, der beim Eingeben der Temperaturwerte für jeden Monat eingegeben wurde. Wie kann ich das Programm dazu bringen, den Monat mit dem höchsten Eintrag anstelle des höchsten Eintrags selbst zurückzugeben?Zurückgeben von Werten aus einem zweiten Array

import java.util.Scanner; 

public class Reader { 

static String months[] = 
    { 
      "January" , "February" , "March" , "April" , "May" , 
      "June", "July", "August", "September", "October", "November", 
      "December" 
    }; 

public static void main(String[] args){ 

    int[] avgMonth; 
    int tempRecords = 0; 
    double tempSum = 0; 
    double avgTemp; 
    double getHotMonth; 

    //collect user input for avg temp and put into an array with the month 
    Scanner input = new Scanner(System.in); 
    avgMonth = new int[months.length]; 
    for(int i=0; i < months.length; i++){ 
     System.out.println("Enter the average temperature for the month of "+months[i]); 
     avgMonth[i] = input.nextInt(); 
    } 


    //call avgTemp, takes array of temps as argument, return total avg for year 
    for(int i=0;i<months.length; i++) 
     tempSum += avgMonth[i]; 

    avgTemp = tempSum/months.length; 

    //call getHotMonth, takes entire array as argument, find index of hottest month 
    getHotMonth = avgMonth[0]; 
    for (int i=0;i<months.length;i++){ 
     if (avgMonth[i] > getHotMonth) 
      getHotMonth = avgMonth[i]; 
    }  

    //displayResults, display average and hottest month 
    //args are average and the index array number of hottest month 
    //final output 

    displayResults(avgTemp,getHotMonth); 

    input.close(); 

}//close main 

public static void displayResults(double average, double getHotMonth){ 
    System.out.println("The average temperature for the year was "+average+" degrees F with "+getHotMonth+" being the hottest month."); 

} 
} 

Antwort

0

Sie müssen die hotMonth als auch während der Iteration erfassen und sie als Argument an displayResults Methode senden, wie unten dargestellt:

public static void main(String[] args){ 

    //add your existing code 

    String hotMonth=""; 
    for (int i=0;i<months.length;i++){ 
     if (avgMonth[i] > getHotMonth) { 
      getHotMonth = avgMonth[i]; 
      hotMonth = months[i];//capture hotMonth 
     } 
    }  
    displayResults(avgTemp,hotMonth); 
    } 

    public static void displayResults(double average, String hotMonth){ 
    System.out.println("The average temperature for the year 
     was "+average+" degrees F with "+ 
     hotMonth+" being the hottest month."); 
    } 
+0

Das ausgedruckte Ergebnis verließ das hotMonth Ergebnis leer, es wurde nichts aus es in der abschließenden Aussage. Weißt du, was das Problem wäre? – squirrel

Verwandte Themen