无法从数组获取indexOf()

问题描述 投票:0回答:1

我是 Java 新手,我正在尝试为我的班级做这个项目,但是最后一个小时我一直停留在一个部分上。我试图调用“fromCity”数组下的变量索引,但全部返回为“-1”。我不确定它为什么这样做,因为在第二个数组“toCity”中我在获取索引时没有问题。谢谢您的帮助。

    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]);




        }
    }
java arrays string indexof
1个回答
0
投票

主要问题是你的

fromCity
是空的。您实际上尚未填充
fromCity
ArrayList
。函数
Arrays.asList
被调用,但结果未分配给
fromCity
。顺便说一句:
asList(fromCity)
毫无意义,因为它已经是
ArrayList
,所以
fromCity.indexOf(city1)
就足够了。 最后,如果没有找到任何一个城市,您将面临
ArrayIndexOutOfBoundsException
,因为您在使用它之前没有检查索引是否为
-1

© www.soinside.com 2019 - 2024. All rights reserved.