尝试添加最小和最大输出

时间:2015-06-25 14:06:39

标签: java max min

我已经阅读了一些他们看起来很有帮助的建议答案,但对我来说太过复杂,无法自信地理解并添加到我的程序中。

有人可以建议从第1年和第2年的销售数据中输出最小值和最大值吗?

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");
  }

}

2 个答案:

答案 0 :(得分: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]);

答案 1 :(得分:0)

要获得最小值,只需保留currentMin,每次迭代时,都要比较循环sales[counter]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);