我正在编写一种方法,通过将第二个数组中两个城镇的索引之间的所有条目相加来计算给定数组中两个城镇之间的距离,但是我无法在第一个数组上调用indexOf来确定添加的位置应该开始。 Eclipse给了我错误“无法在数组类型String []上调用indexOf”,这似乎很简单,但是我不明白为什么这行不通。
请注意,该程序肯定不完整。
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
方法来查找元素。