92.7k views
3 votes
Java Coding help please this is from a beginner's class(I AM DESPERATE)

The info is added in the picture

Java Coding help please this is from a beginner's class(I AM DESPERATE) The info is-example-1
User Sourcey
by
7.7k points

1 Answer

3 votes

Answer:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.*;

class Main {

public static void main(String[] args) {

try {

Scanner scanner = new Scanner(new File("scores.txt"));

int nrAthletes = scanner.nextInt();

ArrayList<String> athletes = new ArrayList<String>();

int winnerIndex = 0;

Double highestAverage = 0.0;

for(int i=0; i<nrAthletes; i++) {

// Get the name of the athlete as the first item

String athleteName = scanner.next();

athletes.add(athleteName);

// Start collecting scores

ArrayList<Double> scores = new ArrayList<Double>();

while(scanner.hasNextDouble()) {

scores.add(scanner.nextDouble());

}

// Remove lowest and highest

scores.remove(Collections.min(scores));

scores.remove(Collections.max(scores));

// Calculate average

double sum = 0.0;

for(double score: scores) {

sum += score;

}

Double averageScore = sum / scores.size();

// Keep track of winner

if (averageScore >= highestAverage) {

highestAverage = averageScore;

winnerIndex = i;

}

// Output to screen

System.out.printf("%s %.2f\\", athleteName, averageScore );

}

// Output winner

System.out.printf("Winner: %s\\", athletes.get(winnerIndex) );

scanner.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

Step-by-step explanation:

Of course this code lacks error handling, but it shows an approach using the scanner object and array lists.

User Dlean Jeans
by
9.9k points