1

I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexes 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] ){
            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;
}
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user5610178
  • 13
  • 1
  • 3

3 Answers3

1

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.

Little Santi
  • 8,563
  • 2
  • 18
  • 46
1

It doesn't work because Java is not JavaScript.

The latter offers an array prototype that actually exposes the function indexOf, while the former does not.

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

Anyway, you can be interested in the ArrayList class in Java (see here for further details) that is more similar to what you are looking for.

skypjack
  • 49,335
  • 19
  • 95
  • 187
-1

How about this (from 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)

I hope this helps you. If it doesn't, please downvote.

Community
  • 1
  • 1
Henry Sanger
  • 143
  • 2
  • 15