gpt4 book ai didi

java - 如何找到数组中元素的索引?

转载 作者:行者123 更新时间:2023-11-29 06:53:11 24 4
gpt4 key购买 nike

我正在尝试解决 this问题:

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

基本上有2个数组,一个是名字,一个是时间,数组索引是匹配的(例如Elena的时间是341),我要找到跑得最快的人,所以谁的时间最小就是最快的。

首先我找到了 times 数组中的最小值。

for (int i = 0; i < array.length; i++) {
if(times[i] < fastest)
fastest = times[i];
}

但我不知道如何匹配名称数组和时间数组,我试过了但是没有用

System.out.println(Arrays.asList(names).indexOf(fastest));

最佳答案

怎么样:

public class test {


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 fastest = Integer.MAX_VALUE;
int slowestRunnner = 0;

for (int i = 0; i < times.length; i++) {
if(times[i] < fastest)
{
fastest = times[i];
slowestRunnner = i;
}
}

System.out.println(names[slowestRunnner]);
}
}

System.out.println(names[slowestRunner]);

关于java - 如何找到数组中元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41025440/

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