2015-06-25 39 views
0

我已經閱讀了一些建議的答案,他們似乎很有幫助,但對我來說太複雜了,無法自信地理解並添加到我的程序中。試圖添加最小和最大輸出

任何人都可以建議如何輸出第一和第二年銷售數字的最小值和最大值?

import java.util.Scanner; 

public class assignment2 
{ 

    public static void main(String[] args) 
    { 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("Welcome!\n"); 
     System.out.println("Month 0 - January"); 
     System.out.println("Month 11 - December\n"); 
     System.out.println("MonthNo(year1)\tSales made\n"); 

     double sales[] = { 60, 54, 62, 67, 54, 67, 51, 50, 62, 55, 49, 70 }; 
     int sum = 0; 
     int average12 = 0; 

     for (int counter = 0; counter < sales.length; counter++) 
     { 
      sum += sales[counter]; 
      System.out.println(counter + "\t\t\t\t\t\t" + sales[counter]); 
     } 

     System.out.println("\nTotal year 1 sales " + sum + "\n"); 

///////////////////////////////////////////////////////////////// 

    System.out.println("MonthNo(year2)\tSales made\n"); 

    double sales2[] = { 59, 43, 48, 51, 49, 57, 39, 42, 54, 51, 60, 62 }; 
    int sum2 = 0; 

for (int counter = 0; counter < sales2.length; counter++) 
     { 
     sum2 += sales2[counter]; 
     System.out.println(counter + "\t\t\t\t\t\t" + sales2[counter]); 
    } 

    System.out.println("\nTotal year 2 sales " + sum2 + "\n"); 
    } 

} 

回答

0

爲了讓您的陣列的最大和最小銷售,你可以使用java.util.Arrays.sort到數組排序,然後最小銷售將是數組的第一個元素和最大的銷售會的最後一個元素陣列。

示例 -

Arrays.sort(sales); 
System.out.println("\nLowest Sales Year1 " + sales[0]); 
System.out.println("\nHighest Sales Year1 " + sales[sales.length-1]); 
Arrays.sort(sales2); 
System.out.println("\nLowest Sales Year2 " + sales2[0]); 
System.out.println("\nHighest Sales Year2 " + sales2[sales2.length-1]); 
+0

這確實有道理,我嚴格地只允許使用掃描儀工具,所以不能使用數組排序工具。有一種更簡單的方法嗎? – r0wl4nd

0

爲了得到最小值,只要保持currentMin,每次你迭代,你在循環sales[counter] VS的currentMin比較當前值。從這裏,你應該能夠得到max

double currentMin = sales[0]; 
for (int counter = 0; counter < sales.length; counter++) { 
    sum += sales[counter]; 
    System.out.println(counter + "\t\t\t\t\t\t" + sales[counter]); 

    //compare 
    if(sales[counter] < currentMin) { 
     currentMin = sales[counter]; 
    } 
} 
System.out.println("Min is " + currentMin);