I have two arrays, one is a String array full of marathon runners and the next is an Integer array full of the marathon runners' respective times. I'm trying to output the fastest runner + his/her time as well as the second fastest runner + his/her time. So far, I've been able to output the fastest runner and his time, but when I try to output the second fastest runner + her time, the loop outputs two runners' times instead of one. I've attached the code for reference:
Also, any comments in terms of simplifying/improving the code is also welcome.
public class APCS {
public static void main(String[] arguments) {
String[] names = {
"Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex",
"Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda",
"Aaron", "Kate"
};
int[] times = {
341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299,
343, 317, 265
};
int timeIndex = 0;
int secondTimeIndex = 0;
for (int i = 0; i < times.length; i++) {
if (times[i] > times[timeIndex]) {
timeIndex = i;
System.out.println(names[timeIndex] + " " + times[timeIndex]);
}
if (times[i] > times[secondTimeIndex]) {
if (times[i] == times[timeIndex]) {
continue;
}
secondTimeIndex = i;
System.out.println(names[secondTimeIndex] + " " + times[secondTimeIndex]);
}
}
}
}
This is my output:
Phil 445
Matt 402
Jane 412
class Runner implements Comparable<Runner>type class that holds String name and int time fields, and then sort the array or List. Or better still, use aComparator<Runner>.