首页 > 解决方案 > 对如何在 Java 中使用数组中的索引和值感到困惑

问题描述

public static double getDistance(int position) {
    
    double distance[] = {64, 63.3, 109, 87.9, 81.2, 73.9, 70.5, 107};
    double distanceInKM = 0;
    int index = 0;
    
    for(int i = 0; i < distance.length; i++) {
        
        if(position == distance[i]) {
            
            distanceInKM = distance[i] * 1.60934;
        }
    }
    return distanceInKM;
}

上面的代码应该接受一个 int 位置,将其与数组中的值进行比较,并根据位置,使用上面的转换将给定位置的值转换为公里。我对如何让位置与数组的索引而不是直接使用值感到困惑。

我已经研究过 indexOf 的使用,但这根本没有帮助(我尝试做 Arrays.asList(distance).indexOf(distance[i]) 而不仅仅是 distance[i],它没有用)。

我对如何首先将位置与数组的索引进行比较,然后获取该索引处的值并对其进行计算感到困惑。任何帮助表示赞赏。

一个适当的示例运行将是:

获取距离(2)-> 109 * 1.60934 = 175.42...

标签: javaarrays

解决方案


在认为你直接调用索引而不是比较它。只要确保检查长度。如下 :

public static double getDistance(int position) {
    
    double distance[] = {64, 63.3, 109, 87.9, 81.2, 73.9, 70.5, 107};
    double distanceInKM = 0;
    
    if(position < distance.length) {
        distanceInKM = distance[position] * 1.60934;
    }

    return distanceInKM;
}

推荐阅读