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

huangapple go评论62阅读模式
英文:

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 &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

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

    return distanceInKM;
}

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

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定