Search code examples
javaarraysstringindexof

Cannot get indexOf() from array


I'm new to Java and I'm trying to do this project for my class however I've been stuck for the last hour on one single part. I'm trying to call the index of the variables under the "fromCity" array, however the all come back as "-1". I'm not sure why it is doing this because in the second array "toCity" I am having no issues in getting the index. Thank you for the help.

    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.Arrays;
    import static java.util.Arrays.asList;

    public class EX07_2 {
        public static void main(String[] args){
           Scanner scanner = new Scanner(System.in);
           ArrayList<String> fromCity = new ArrayList<>();
                Arrays.asList("Los Angeles", "San Francisco", "Portland");

            String[] toCity;
            toCity = new String[3];
            toCity[0] = "Seattle";
            toCity[1] = "Denver";
            toCity[2] = "Chicago";

            int [][] distance = new int[3][3];
            distance [0][0] = 1135;
            distance [0][1] = 1016;
            distance [0][2] = 2015;
            distance [1][0] = 807;
            distance [1][1] = 1250;
            distance [1][2] = 2128;
            distance [2][0] = 174;
            distance [2][1] = 1240;
            distance [2][2] = 2121;


            System.out.println("Enter the name of a city to travel from: ");
            String city1 = scanner.nextLine();
            System.out.println("Enter the name of a city to travel to: ");
            String city2 = scanner.nextLine();
            int index1 = asList(fromCity).indexOf(city1);
            int index2 = asList(toCity).indexOf(city2);

            System.out.println(distance[index1][index2]);




        }
    }

Solution

  • The main issue is that your fromCity is empty as the result of Arrays.asList is not assigned to fromCity. The indentation of your code is somehow misleading here, as one can be tricked into thinking this is a chained call, but it is not.

    Also, as fromCity is already an ArrayList using asList(fromCity) is rather pointless and you you can get the index directly by fromCity.indexOf(city1).

    BTW: you will face ArrayIndexOutOfBoundsException if either city is not found because you don't check if index is -1 prior using it.