view raw
user5610178 user5610178 - 6 months ago 33
Java Question

Cannot invoke indexOf on an Array of strings?

In a first year cs course so please bare with me. Pretty basic question but i couldn't find an answer for it. I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexs of the two towns in the second array, but I can't invoke indexOf on the first array to determine where the addition should start. Eclipse is giving me the error "Cannot invoke indexOf on array type String[]" which seems pretty straight forward, but i do not understand why that won't work.
Please note the program is definitely not complete.

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] ){
//Loop is executed if the towns are in the array, this loop should return the distance
for(int j=0; j<towns.length; j++){
*int distance1=towns.indexOf(word1);*

return distance;


No, arrays do not have any methods you can invoke. If you want to find the index of an given element, you can replace String[] by ArrayList<String>, which has an indexOf method to find elements.