java - 对如何在 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...
解决方案
在认为你直接调用索引而不是比较它。只要确保检查长度。如下 :
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;
}
推荐阅读
- curl - Curl to Python 上传到 Galaxy Store 的请求
- html - 当宽度不足时,如何使 CSS Grid 项目(具有不同宽度)换行到 100%?
- gnuplot - Gnuplot 根据 Matrix 数据在极坐标中绘制 2D 热图
- latex - Latex 中数学方程的目录
- c# - C# 上的 System.Data 表数据类型修复
- webpack - 无效的选项对象。Image Minimizer Plugin 已使用与 API 架构不匹配的选项对象进行初始化
- python - 为数据帧的每一行获取字符串的第一部分
- docker - 如何使用 ansible 从不安全的 docker 注册表中提取?
- tableau-api - Tableau 作业的事件管理
- angular - 如果用户通过(shift + tab)聚焦在场外,如何防止调用聚焦方法