[英]Computing Month & Monthly Sales in Java
computeHighestMonth(monthlySales)
此方法接收每月销售数组作为参数。 此方法将搜索并比较每月销售额数组中的最大值。 该方法将返回具有最大值的月份的索引(或数组中的位置)。
我有它,以便它将显示最高的销售额,但我不知道如何包括月份名称。
public static double computeHighestMonth(double[] monthlySales)
{
double highestSales = 0;
for (int index = 0; index < monthlySales.length; index++)
{
if (monthlySales[index] > highestSales)
highestSales = monthlySales[index];
}
return highestSales;
}
您不仅应保留highestSales,还应保留其存储的索引值。 这意味着您应该声明一个整数,该整数应每次更新
monthlySales[index] > highestSales
是真的。 这样,您将保留“月数”,然后将其转换为所需的字符串。
希望这可以帮助!
您还需要保存索引:
public static double computeHighestMonth(double[] monthlySales)
{
double highestSales = 0;
int month = 0;
for (int index = 0; index < monthlySales.length; index++)
{
if (monthlySales[index] > highestSales){
highestSales = monthlySales[index];
month = index + 1;
}
}
System.out.print("The salary was highest on: ");
switch(month){
case 1: System.out.println("January");
case 2: System.out.println("February");
etc.
}
return highestSales;
}
只需返回该值的索引,而不是返回highestSales
,然后使用该索引就可以提供月份和最大值:
public static int computeHighestMonth(double[] monthlySales) {
double highestIndex = 0;
for (int index = 0; index < monthlySales.length; index++) {
if (monthlySales[index] > monthlySales[highestIndex])
highestIndex = index;
}
return highestIndex;
}
然后使用返回的值获取月份及其值,如下所示:
highestIndex = computeHighestMonth(monthlySales);
System.out.println("the highest value is: "+monthlySales[highestIndex]+" of the month "+highestIndex+1);
如果您的monthlySales
数组为List<Double>
会更容易,因为您可以使用
List<Double> monthlySales = ...;
Double highestSales = Collections.max(monthlySales);
这将使您以String
月份,即一月,二月等。根据您的要求,而不是返回double
精度值,您可以返回键值对或String
例如, month + " had the highest sales " + highestSales
public static double computeHighestMonth(double[] monthlySales)
{
double highestSales = 0;
String month = "";
DateFormatSymbols dfs = new DateFormatSymbols();
for (int index = 0; index < monthlySales.length; index++)
{
if (monthlySales[index] > highestSales) {
highestSales = monthlySales[index];
month = dfs.getMonths()[index];
}
}
System.out.println(month);
return highestSales;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.