我在作业中迷失了方向,需要帮助!基本上,我想编写一个代码,用户可以输入 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();
}
}
}
最佳答案
对于格式问题,请这样做:
System.out.println("The total rainfall for this year is " +
formatter.format(totalRain(rainFall)));
等等所有返回值。
我不明白有关月份的问题。您能再解释一下吗?
编辑。好的,我明白了。当您分配 higuestRain,... 值时,循环内的 index
值将是您要搜索的月份; )
关于java - 需要在数组中引用和数字格式方面的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481563/