我在一项任务中迷失了方向,需要帮助!基本上,我想编写一个代码,用户可以在其中输入 12 个月内每月降雨的英寸数。它将计算总英寸、平均英寸,并指出降雨最多和最少的月份。我控制了总英寸和平均英寸。
不过,最多和最少的雨是我遇到问题的地方。我知道如何编写代码来计算最高和最少的降雨量,但我不知道如何让它实际说出输出中的哪个实际月份。它希望我在 12 个月的数组中列出实际数字,例如,第七个月为 7。
我遇到的另一个问题是十进制格式。我把 import 语句放在了顶部,我把我认为正确的代码放在了我认为正确的地方,但是当计算平均值时,它仍然会产生一长串数字。即 12.12121314141,当我希望它显示 12.1 时。
任何帮助将不胜感激。先感谢您!这是代码:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main (String [] args)
{
final int MONTHS = 12;
double[] rainFall = new double[MONTHS];
initRain(rainFall);
DecimalFormat formatter = new DecimalFormat("##0.0");
System.out.println("The total rainfall for this year is " +
totalRain(rainFall));
System.out.println("The average rainfall for this year is " +
averageRain(rainFall));
System.out.println("The month with the highest amount of rain is " +
highest);
System.out.println("The month with the lowest amount of rain is " +
leastRain(rainFall));
}
/**
totalRain method
@return The total rain fall in the array.
*/
public static double totalRain(double[] rainFall)
{
double total = 0.0; // Accumulator
// Accumulate the sum of the elements in the rain fall array
for (int index = 0; index < rainFall.length; index++)
//total += rainFall[index];
total = total + rainFall[index];
// Return the total.
return total;
}
/**
averageRain method
@return The average rain fall in the array.
*/
public static double averageRain(double[] rainFall)
{
return totalRain(rainFall) / rainFall.length;
}
/**
mostRain method
@return The most rain in the rain fall array.
*/
public static double mostRain(double[] rainFall)
{
double highest = rainFall[0];
for (int index = 0; index < rainFall.length; index++)
{
if (rainFall[index] > highest)
highest = rainFall[index];
}
return highest;
}
/**
leastRain method
@returns The least rain in rain fall array.
*/
public static double leastRain(double[] rainFall)
{
double lowest = rainFall[0];
for (int index = 0; index < rainFall.length; index++)
{
if (rainFall[index] < lowest)
lowest = rainFall[index];
}
return lowest;
}
/**
initRain method
@return The rain fall array filled with user input
*/
public static void initRain(double[] array)
{
double input; // To hold user input.
Scanner scan = new Scanner(System.in);
for (int index = 0; index < array.length; index++)
{
System.out.print("Enter rain fall for month " + (index + 1)
+": ");
array[index] = scan.nextDouble();
}
}
}