无法在字符串数组上调用 indexOf?

Cannot invoke indexOf on an Array of strings?

我正在编写一种方法来计算给定数组中两个城镇之间的距离,方法是将第二个数组中两个城镇的索引之间的所有条目相加,但我无法在第一个数组中调用 indexOf以确定添加应该从哪里开始。 Eclipse 给我的错误 "Cannot invoke indexOf on array type String[]" 看起来很简单,但我不明白为什么那行不通。 请注意程序肯定是不完整的。

public class Exercise_3 {
public static void main(String[] args){
    //Sets the array 
    String [] towns={"Halifax","Enfield","Elmsdale","Truro","Springfield","Sackville","Moncton"};
    int[] distances={25,5,75,40,145,55,0};
    distance(towns, distances, "Enfield","Truro");
}
public static int distance(String[] towns,int[] distances, String word1, String word2){
    int distance=0;
    //Loop checks to see if the towns are in the array
    for(int i=0; i<towns.length; i++){
        if(word1!=towns[i] || word2!=towns[i] ){
            distance=-1;
        }
    //Loop is executed if the towns are in the array, this loop should return the distance 
        else{
            for(int j=0; j<towns.length; j++){
                *int distance1=towns.indexOf(word1);*


            }
        }                               
    }
    return distance;
}
}

不,数组没有任何可以调用的方法。如果要查找给定元素的索引,可以将 String[] 替换为 ArrayList<String>,其中 具有 一个 indexOf 方法来查找元素。

它不起作用,因为 Java 不是 JavaScript.

后者提供了一个 array 原型,实际上公开了函数 indexOf,而前者没有。

Arrays in JavaScript are completely different from their counterparts 在 Java.

无论如何,您可能会对 Java 中的 ArrayList class 感兴趣(有关详细信息,请参阅 here),它与您正在寻找的内容更相似.

这个怎么样(来自this post)?

There are a couple of ways to accomplish this using the Arrays utility class.

If the array is not sorted:

java.util.Arrays.asList(theArray).indexOf(o)

If the array is sorted, you can make use of a binary search for performance:

java.util.Arrays.binarySearch(theArray, o)

希望对您有所帮助。如果没有,请投反对票。