我是新來的Java,並已考慮到要求分配:使用陣列式打印的最低和第二最低值的方法(JAVA)
說明
一羣朋友決定運行波士頓馬拉松賽。他們的名字和時間(分鐘)如下:
Name Time(minutes)
Elena 341
Thomas 273
Hamilton 278
Suzie 329
Phil 445
Matt 402
Alex 388
Emma 275
John 243
James 334
Jane 412
Emily 393
Daniel 299
Neda 343
Aaron 317
Kate 265
找到最快的跑步者。打印名稱和他/她的時間(以分鐘爲單位)。
尋找第二快的跑步者。打印名稱和他/她的時間(以分鐘爲單位)。
說明書
編寫作爲輸入整數的數組,並返回對應於 人具有最低時間索引的方法。在時間數組上運行此方法。打印出與返回索引對應的名稱和時間 。 寫第二種方法找到第二好的跑步者。第二種方法應該使用第一種方法 來確定最佳跑步者,然後遍歷所有值以找到第二好的(第二最低)時間。 這裏是一個程序骨架開始:
class Marathon {
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 i1 = fastestIndex(times);
int i2 = secondFastestIndex(times);
//
// your output based on the index i1 and i2
//
}
// your two Java methods:
// fastestIndex() and secondFastestIndex()
}
我寫的打印第一和第二位的時間和名稱,但現在我開始以爲我沒有正確地按照指令的程序。任何人都可以幫我弄清楚我應該做什麼不同嗎?
這裏是我的業餘代碼:
public class Lab
{
public static void main(String[] args)
{
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 firstplace = times[0];
String firstname = names[0];
int secondplace = times[0];
String secondname = names[0];
for (int counter = 0; counter < times.length; counter++)
{
if (times[counter] < firstplace) {
firstplace = times[counter];
firstname = names[counter]; }
}
for (int counter = 0; counter < times.length; counter++)
{
if (times[counter] > firstplace)
if (times[counter] < secondplace) {
secondplace = times[counter];
secondname = names[counter]; }
}
System.out.printf("The fastest runner is: %s (%d Minutes)%n", firstname, firstplace);
System.out.printf("The second fastest runner is: %s (%d Minutes)%n", secondname, secondplace);
} // end main
} // end class Lab
這是它打印:
The fastest runner is: John (243 Minutes)
The second fastest runner is: Kate (265 Minutes)
謝謝你的迴應,這非常有幫助。我認爲有一個我錯過的概念,所以我一直在閱讀教科書和你的代碼,以更好地理解這一點。現在我的代碼正在編譯,但是當我在命令提示符下運行它時,它會掛起而沒有輸出。 – presence
@presence你是否需要進一步的幫助?我上面發佈的代碼在我的eclipse中運行 – HenriqueMS