Java 从第二个数组返回值
当前,我的代码返回用户输入每个月的温度值时提交的最高温度值。如何让程序返回条目最多的月份,而不是返回条目最多的月份Java 从第二个数组返回值,java,arrays,Java,Arrays,当前,我的代码返回用户输入每个月的温度值时提交的最高温度值。如何让程序返回条目最多的月份,而不是返回条目最多的月份 import java.util.Scanner; public class Reader { static String months[] = { "January" , "February" , "March" , "April" , "May" , "June", "July", "August", "Septemb
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.");
}
}
import java.util.Scanner;
公共类阅读器{
静态字符串月份[]=
{
“一月”、“二月”、“三月”、“四月”、“五月”,
“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”,
“12月”
};
公共静态void main(字符串[]args){
int[]平均每月;
int tempRecords=0;
双温和=0;
双avgTemp;
双月;
//收集用户输入的平均温度,并将其放入带有月份的数组中
扫描仪输入=新扫描仪(System.in);
avgMonth=新整数[月长];
对于(int i=0;i 对于(int i=0;i您需要在迭代期间捕获hotmount
,并将其作为参数发送到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.");
}
publicstaticvoidmain(字符串[]args){
//添加现有代码
字符串hotmount=“”;
for(int i=0;i getHotMonth){
getHotMonth=avgMonth[i];
hotmount=months[i];//捕获hotmount
}
}
显示结果(avgTemp、hotMonth);
}
公共静态void显示结果(双倍平均值,字符串热月){
System.out.println(“一年的平均温度
是“+平均值+”华氏度,带“+
hotMonth+“是最热的月份。”);
}
打印出来的结果将hotMonth结果留空,在最终报表中没有任何结果。您知道会出现什么问题吗?