Skip to content
Advertisement

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

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement