简体   繁体   中英

How to us math.max and math.min to omit high and low scores

(this is java) In my method, I am calculating 7 scores given to me in a file. I have to set the a max and min, initialize them that is, where I'm having problems at. Also, i have to use math.max and math.min with my sum. If more of my program is needed please ask. the sample file input is:

public static double calculateDiveScore(String diveLine) {
    Scanner diveLineSc = new Scanner(diveLine);

    int dive = diveLineSc.nextInt();
    double difficulty = diveLineSc.nextDouble();
    double sum = 0.0;
    double max = ;
    double min = ;


    for( int i = 1; i < 7; i++){
        double score = diveLineSc.nextDouble();
        max = Math.max(max,score);
        min = Math.min(min,score);
        sum +=score;

    }

    double totalScore = (sum - max - min )* difficulty * 0.6;

    return totalScore;
}

You need to initialise the variables as follows.

double max = Double.NEGATIVE_INFINITY;
double min = Double.POSITIVE_INFINITY;

It could be because you are only checking 6 numbers, but I don't know what your program is doing. Start I from 0.

Initialize Max and Min as follow

public static double calculateDiveScore(String diveLine) {
Scanner diveLineSc = new Scanner(diveLine);

int dive = diveLineSc.nextInt();
double difficulty = diveLineSc.nextDouble();
double max = diveLineSc.nextDouble();
double min = max;
double sum = max;


for( int i = 1; i < 7; i++){
    double score = diveLineSc.nextDouble();
    max = Math.max(max,score);
    min = Math.min(min,score);
    sum +=score;

}

double totalScore = (sum - max - min )* difficulty * 0.6;

return totalScore;

}

Start the maximum and minimum at the first value, then loop one time fewer.

double first = diveLineSc.nextDouble();
double max = first;
double min = first;
double sum = first;


for (int i = 0; i < 5; i++) {...}

Alternatively, collect your values into an array and use library methods.

double sum = 0;
ArrayList<Double> scores = new ArrayList<Double>();
for (int i = 0; i < 6; i++) {
    double score = diveLineSc.nextDouble();
    scores.add(score);
    sum += score;
}

double min = Collections.min(scores);
double max = Collections.max(scores);

Note that internally, Java will probably perform another loop through the list on the calls to min and max . If your code turns out to be too slow (which I really doubt it will be unless you're dealing with millions of scores), the first algorithm might be more optimized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM