Java数组循环方法返回数组

时间:2018-05-17 00:39:59

标签: java arrays loops for-loop

我制作了一个程序来确定谁在马拉松比赛中有最快的时间和一个相应的名字。为了使它们匹配,我返回最低时间的索引而不是索引的值。当我返回索引的值而不是索引时,它返回正确的名称和时间,但是,当返回索引时,它返回两个数组中的最后一个值。

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

2 个答案:

答案 0 :(得分:2)

for(i = 0; i < time.length; i++)
{
    if(time[i] < bestTime)
    {
        firstValue = i; 
    }
}

在此循环中,您不会更新bestTime,因此所有时间都会与1000的初始值进行比较。它们都很小,导致最后一场胜利。

答案 1 :(得分:2)

您在main中有一个循环,您在其中迭代names以显示所有名称和时间。您可以在该循环中找到最低key。像,

int key = 0;
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i] + ": " + times[i]);
    if (times[i] < times[key]) {
        key = i;
    }
}
System.out.println("In first place is " + names[key] + " with a time of " + times[key] + " minutes!");

,在您当前的方法中,更改

if(time[i] < bestTime)

if (time[i] < time[firstValue])

并消除bestTime