2015-07-13 105 views
0
computeHighestMonth(monthlySales) 

此方法接收每月銷售數組作爲參數。此方法將搜索並比較每月銷售數組的最高值。該方法將返回具有最高值的月份的索引(或數組中的位置)。Java中的計算月和月銷售額

我這樣做,它會顯示最高的銷售額,但我不知道如何包括月份名稱。

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; 
} 
+0

什麼是你給的I/P和你得到的這個代碼是什麼意思格式。 – Satya

+0

不是問題的答案,但由於您正在談論銷售和使用雙打,我建議看看'BigDecimals'; 「浮點」是不準確的。 [LINK1](http://stackoverflow.com/questions/6320209/javawhy-should-we-use-bigdecimal-instead-of-double-in-the-real-world); [LINK2](http://java-performance.info/bigdecimal-vs-double-in-financial-calculations/)。 –

+0

有沒有任何答案對您有幫助?如果是的話,請接受它。 –

回答

0

您不僅應該保存highestSales,還要保存存儲的索引值。這意味着你應該聲明一個應該每次更新的整數

monthlySales[index] > highestSales 

是正確的。這樣您就可以保留哪個是「月份數」,您應該隨後將其轉換爲您需要的字符串。

希望這會有所幫助!

0

您還需要保存索引:

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; 
} 
0

簡單,而不是返回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); 
0

會更容易,如果你的monthlySales陣列將是一個List<Double>,因爲你可以就用

List<Double> monthlySales = ...; 
Double highestSales = Collections.max(monthlySales); 
0

這會給你每月爲String即一月,二月等根據您的requirnments,而不是你返回double您可以返回一個關鍵值對或Stringmonth + " 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; 
    }