gpt4 book ai didi

java - 显示马拉松第一名和第二名获胜者的姓名和时间

转载 作者:行者123 更新时间:2023-12-02 11:12:27 25 4
gpt4 key购买 nike

我需要你们的帮助

/** * 在此作业中,我应该显示马拉松比赛第一名和第二名获胜者(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");

}

}

最佳答案

使用其他集合会很容易..但是您也可以使用简单的数组来做到这一点..不仅是第二个,您可以通过对数组进行排序来找到所有运行者的排名..检查此代码..

     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");
}

关于java - 显示马拉松第一名和第二名获胜者的姓名和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50531301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com