从第二个数组返回值

时间:2017-04-07 17:54:28

标签: java arrays

目前,我的代码返回用户输入每个月的温度值时提交的最高温度值。如何让程序返回具有最高条目的月份,而不是最高条目本身?

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

}
}

1 个答案:

答案 0 :(得分:0)

您需要在迭代期间捕获hotMonth并将其作为参数发送到displayResults方法,如下所示:

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