[英]Why am I getting this error when using add() and getFirst() for a LinkedList?
这是我的代码:
public class FlightMap implements FlightMapInterface {
LinkedList<City> cityList = new LinkedList<City>();
LinkedList<City> nextCity = new LinkedList<City>();
/**
* Creates an empty FlightMap
*/
public FlightMap() {
}
public void loadFlightMap(String cityFileName, String flightFileName)
throws FileNotFoundException {
File cityList = new File(cityFileName);
File flightsTo = new File (flightFileName);
Scanner theCityFile = null;
Scanner theFlightFile = null;
Scanner theRequestFile = null;
ArrayList<String> cityStringList = new ArrayList<String>();
int counter = 0;
try {
theCityFile = new Scanner (cityList);
theFlightFile = new Scanner (flightsTo);
}
catch (FileNotFoundException e) {
System.out.println("No such file exists.");
}
while (theFlightFile.hasNextLine()) {
cityStringList.add((theFlightFile.nextLine()).replaceAll("\t", ""));
}
while (theCityFile.hasNextLine()) {
LinkedList<City> tempList = new LinkedList<City>();
String tempCity = theCityFile.nextLine();
nextCity.add(tempList); // ERROR
nextCity.get(counter).add(new City(tempCity)); // ERROR
for (int x = 0; x < cityStringList.size(); x++) {
if (cityStringList.get(x).charAt(0) == tempCity.charAt(0)) {
insertAdjacent(nextCity.get(counter).getFirst(), // ERROR
new City(cityStringList.get(x)).charAt(1) + ""); // ERROR
}
}
cityList.add(new City(tempCity)); // ERROR
counter++;
}
}
对于我的错误:
错误确切地说。
LinkedList<City> tempList = new LinkedList<City>();
String tempCity = theCityFile.nextLine();
nextCity.add(tempList);
应该是
String tempCity = theCityFile.nextLine();
nextCity.add(tempCity);
您试图将LinkedList
添加到另一个LinkedList
。 您只能将City
类型的“节点”添加到声明的LinkedList
中。
您不能add()
列表add()
到LinkedList<City>
-它的元素必须是City
类型,而不是List<City>
类型。 您可以改用addAll
。 然后,您尝试add
City
add
到City
而不是List
-显然City
没有Add
方法。 同样,使用getFirst
和charAt
将City
对象当作List
或String
对待。
您正在尝试做一些没有意义的事情,因此您会遇到这些错误。
LinkedList类型的方法add(City)不适用于参数(LinkedList)
您正在尝试将城市列表添加到城市列表中。
未为城市类型定义方法add(City)
您正在尝试将城市添加到城市(而不是城市列表),但尚未定义这种方法。
对于城市类型,未定义方法getFirst()对于城市类型,未定义方法charAt(int)
您尚未定义这些方法,因此无法调用它们。
在此代码中:
LinkedList<City> tempList = new LinkedList<City>();
String tempCity = theCityFile.nextLine();
nextCity.add(tempList);
您试图将LinkedList<City>
添加到您的nextCity
列表中,这是错误提示的内容。
首先,nextCity的类型为LinkedList <City>,因此您无法向其中添加LinkedList:
nextCity.add(tempList);
改用:
nextCity.addAll(tempList);
同样的问题是:
nextCity.get(counter).add(new City(tempCity));
您正在获得城市,并再次向其添加城市。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.