我需要编写一个程序来存储12个月的总降雨量,然后显示总量,平均值,最高降雨量和最低降雨量的月份输出。我的程序运行但是我不知道如何使输出成为月份的数量,而不是那个月的降雨量。 例如,当我有,输入第6个月的降雨:15.6我的输出应该是6而不是15.6。谢谢你的帮助。
import java.util.Scanner;
public class Rainfall
{
public static void main (String [] args)
{
double[] rain = new double[12]; // The rainfall data
getValues(rain);
showValues(rain);
System.out.println("The total rainfall for this year is: " + totalRain(rain));
System.out.println("The average rainfall for this year is: " + averageRain(rain));
System.out.println("The month with the highest amount of rain is: " + mostRain(rain));
System.out.println("The month with the lowest amount of rain is: " + leastRain(rain));
}
/**
showValues method
@param rain Display the rainfall array
*/
public static void showValues(double[] rain)
{
}
/**
getValues method
@return The rain array filled with user input
*/
public static void getValues(double[] array)
{
Scanner scan = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.println("Enter rain fall for month " + (i + 1) + ".");
array[i] = scan.nextDouble();
}
}
/**
getTotal method
@return The total of the elements in
the rainfall array.
*/
public static double totalRain(double[] rain)
{
double total = 0.0; // Accumulator
// Accumulate the sum of the elements
// in the rainfall array.
for (int index = 0; index < rain.length; index++)
//total += sales[index];
total = total + rain[index];
// Return the total.
return total;
}
/**
getAverage method
@return The average of the elements
in the rainfall array.
*/
public static double averageRain(double[] rain)
{
return totalRain(rain) / rain.length;
}
/**
getHighest method
@return The highest value stored
in the rainfall array.
*/
public static double mostRain(double[] rain)
{
double highest = rain[0];
for (int index = 1; index < rain.length; index++)
{
if (rain[index] > highest)
highest = rain[index];
}
return highest;
}
/**
getLowest method
@returns The lowest value stored
in the rainfall array.
*/
public static double leastRain(double[] rain)
{
double lowest = rain[0];
for (int index = 1; index < rain.length; index++)
{
if (rain[index] < lowest)
lowest = rain[index];
}
return lowest;
}
}
答案 0 :(得分:0)
这是一个使用JAVA 8 Streams的非常简单的方法:
Double[] doubles = new Double[12];
List<Double> doubleList = Arrays.asList(doubles);
Double max = doubleList.stream().mapToDouble(dub -> dub).max().getAsDouble();
Double min = doubleList.stream().mapToDouble(dub -> dub).min().getAsDouble();
答案 1 :(得分:0)
试试这个:不是指定索引的下雨量,而是想要索引istelf。
public static double mostRain(double[] rain)
{
double highest = rain[0];
int highestMonth = 0;
for (int index = 1; index < rain.length; index++)
{
if (rain[index] > highest)
highest = rain[index];
highestMonth = index;
}
return highestMonth;
}