# 在Java中如何同时处理数组中的索引和值感到困惑

go评论63阅读模式

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

``````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 &lt; 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

``````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 &lt; distance.length) {
distanceInKM = distance[position] * 1.60934;
}

return distanceInKM;
}
``````

• 本文由 发表于 2020年10月6日 13:35:19
• 转载请务必保留本文链接：https://go.coder-hub.com/64219926.html
• arrays
• java

go 52

go 62

go 97

go 78