BlueJ的Min Max

时间:2017-03-28 03:16:22

标签: bluej

我正在从我的大学做我的作业,但我正在努力解决这个问题:读入整数直到用户输入-1。如果至少有3个值,则显示除最大和最小数字之外的平均值。 这是我的代码,但似乎没有摆脱最大和最小的数字来获得平均值。

import java.util.Scanner;
public class MiddleAverage {
    public static void main(String[] args) {
        int sum;
        int count;
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        double average;
        sum = 0;
        count = 0;
        average = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Value: ");
        int value = scanner.nextInt();
        while ( value != -1)
        {
            if ( value < min )
            min = value;

            if ( value > max )
            max = value;

            System.out.print("Value: ");
            value = scanner.nextInt();
            count++;
            sum = sum + value;
            average = sum / count;
        }
        if (value == -1)
        {
            System.out.println("Middle average is: " + average);
        }



    }
}

您对此有什么想法请向我解释。谢谢!

1 个答案:

答案 0 :(得分:0)

在您的代码中,您每次输入值时都会计算平均值,这有点浪费,因为您只需要最后的平均值。 (而且它也很难删除min&amp; max!)

我对您的代码进行了一些更改,请看一下:

int sum = 0, count = 0; // Condensed a few lines

int min = Integer.MAX_VALUE; 
int max = Integer.MIN_VALUE;

Scanner scanner = new Scanner(System.in);
int value;

System.out.print("Value: ");
value = scanner.nextInt();

while (value != -1) {

    if ( value < min )
        min = value;

    if ( value > max )
        max = value;

    count++;
    sum = sum + value;

    System.out.print("Value: ");
    value = scanner.nextInt();
}

// You don't need to check if it's -1 because it MUST be in order to leave the loop
if (count >= 3) {
    System.out.println("Middle average is: " + (sum - max - min) / (count - 2));
} else {
    // Less then 3 values
}

干杯!