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;
}
}
2
  • 1
    arrays dont have an indexOf method. Commented Nov 26, 2015 at 23:00
  • Java is not JavaScript. Commented Nov 26, 2015 at 23:03

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.