Java项目中fromCity集合调用indexOf()始终返回-1问题求助
问题分析与解决
核心问题
你的fromCity集合始终为空,且后续调用asList(fromCity)的方式错误,导致indexOf()返回-1:
- 创建空的
ArrayList<String> fromCity后,单独调用Arrays.asList(...)但未将结果赋值或添加到fromCity中,导致集合内无任何城市元素。 asList(fromCity)是把整个ArrayList对象作为单个元素包装成List,而非将集合内的元素转成List,自然无法匹配输入的城市名称。
而toCity是数组,asList(toCity)会正确将数组元素转为List,所以indexOf()能正常工作。
修正后的代码
import java.util.ArrayList; import java.util.Scanner; import java.util.Arrays; public class EX07_2 { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); // 直接用Arrays.asList的结果初始化fromCity,确保集合包含指定城市 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(); // 直接调用fromCity的indexOf方法,无需再用asList包装 int index1 = fromCity.indexOf(city1); int index2 = Arrays.asList(toCity).indexOf(city2); // 添加索引合法性判断,避免输入不存在的城市导致数组越界 if(index1 != -1 && index2 != -1){ System.out.println(distance[index1][index2]); } else { System.out.println("输入的城市名称不存在"); } } }
关键修正点
- 初始化fromCity:通过
new ArrayList<>(Arrays.asList(...))直接将城市元素添加到集合中,确保集合非空。 - 获取index1:直接使用
fromCity.indexOf(city1),因为fromCity本身就是List实现类,自带indexOf()方法。 - 新增合法性判断:避免用户输入不存在的城市时,出现数组越界异常。
内容的提问来源于stack exchange,提问作者beansies
相关产品推荐
相关产品推荐

