【发布时间】:2018-05-17 00:39:59
【问题描述】:
我正在编写一个程序来确定谁在马拉松比赛中跑得最快,这是从一组时间和一个相应的名称中得出的。为了使它们匹配,我返回最低时间的索引而不是索引的值。当我返回索引的值而不是索引时,它返回正确的名称和时间,但是,当返回索引时,它返回两个数组中的最后一个值。
package Lec3;
public 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
};
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i] + ": " + times[i]);
}
int key = firstPlace(times, names);
System.out.println("In first place is " + names[key] + " with a time of " + times[key] + " minutes!");
}
public static int firstPlace(int[] time, String[] names)
{
int i;
int bestTime = 1000;
int firstValue = 0;
for(i = 0; i < time.length; i++)
{
if(time[i] < bestTime)
{
firstValue = i;
}
}
return firstValue;
}
}
【问题讨论】:
-
更好的解决方案 -> 使用哈希
标签: java arrays loops for-loop