英文:
Confused on how to work with both indexes and values in an array in 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;
if (position >= 0 && position < distance.length) {
distanceInKM = distance[position] * 1.60934;
}
return distanceInKM;
}
以上代码用于接受一个整数位置(position),将其与数组中的值进行比较,然后基于位置将给定位置处的值转换为千米,使用上述的转换率。如果您想要通过索引访问数组中的值,只需检查位置是否在合法的索引范围内,然后使用该位置作为索引来访问数组中的值,并执行相应的计算。
英文:
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;
}
The above code is supposed to accept an int position, compare it to the values in the array, and based on the position, convert the value at the given position to Kilometers using the conversion above. I am confused on how to get the position to work with the index of the array instead of just the values directly.
I have looked into the use of indexOf, but that does not help at all (I tried doing Arrays.asList(distance).indexOf(distance[i]) instead of just distance[i], it did not work).
I am confused on how to first compare the position to the indexes of the array, and then get the value at that index and do the calculation on it. Any help is appreciated.
A proper example run would be:
getDistance(2) ->
109 * 1.60934 = 175.42...
答案1
得分: 3
我认为你可以直接调用索引,而不是进行比较。只需确保检查长度。如下所示:
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;
}
英文:
In think you directly call the index rather than comparing it. Just make sure to check the length. As below :
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论