我想在这里帮助你们
/ ** *在这项任务中,我应该显示马拉松赛的第一和第二名获胜者(2个最佳时间)的名称和时间 *但我正在努力与第二个 * /
public class MitAssignment3Chapter7 {
public static void main(String args[]){
String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
int[] timeInMinutes = {40,50,76,56,62};
int index = 0;
int a = 0;
int first = timeInMinutes[1];
for (a = 0 ; a < timeInMinutes.length; a++){
if ( first > timeInMinutes[a]){
index = a;
first = timeInMinutes[index];
}
// if (first < timeInMinutes[a] && timeInMinutes[a]) Trying to do the second here
}
System.out.println("The winner of the marathon is: "+runners[index]+" with "+timeInMinutes[index]+" minutes");
}
}
答案 0 :(得分:1)
使用其他集合会很容易..但你也可以用简单的数组来做..不仅第二个,你可以通过排序数组找到所有的跑步者等级..检查这个代码..
public static void main(String args[]) {
String runners[] = { "Gene", "Elvis", "Presley", "Felicity", "Welcome" };
int[] timeInMinutes = { 40, 50, 76, 56, 62 };
int a = 0;
int tempTime = 0;
String tempRunner = "";
for (int i = 0; i < timeInMinutes.length; i++) {
for (int j = i + 1; j < timeInMinutes.length; j++) {
if (timeInMinutes[i] > timeInMinutes[j]) {
tempTime = timeInMinutes[i];
timeInMinutes[i] = timeInMinutes[j];
timeInMinutes[j] = tempTime;
tempRunner = runners[i];
runners[i] = runners[j];
runners[j] = tempRunner;
}
}
}
for (int index = 0; index < runners.length; index++)
System.out.println("Rank " + (index+1) + ": " + runners[index] + " with " + timeInMinutes[index] + " minutes");
}
答案 1 :(得分:0)
你可以先找到胜利者,在你找到胜利者之后,从你的时间阵列中取出胜利者并找到当前阵列中最快的人,它将成为第二个玩家。
答案 2 :(得分:0)
您可以创建一个新类来保存结果时间和名称。为此类实现compareTo
方法。使用所有结果填充新List
并对其进行排序。现在可以获得任何Nth
结果(时间和名称)。
static class Result implements Comparable<Result> {
private final int time;
private final String name;
Result(int time, String name) {
this.time = time;
this.name = name;
}
int getTime() { return time; }
String getName() { return name; }
@Override
public int compareTo(Result o) {
return Integer.compare(time, o.time);
}
}
public static void main(String args[]){
String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
int[] timeInMinutes = {40,50,76,56,62};
List<Result> results = new ArrayList<>(runners.length);
for (int i = 0; i < runners.length; i++) {
results.add(new Result(timeInMinutes[i], runners[i]));
}
Collections.sort(results);
Result second = results.get(1);
System.out.println("Second winner: " + second.getName() + "; Time: " + second.getTime());
}